answer
stringlengths
17
10.2M
package jlibs.core.nio; import jlibs.core.lang.ImpossibleException; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import static java.nio.channels.SelectionKey.OP_READ; import static java.nio.channels.SelectionKey.OP_WRITE; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.*; import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW; /** * @author Santhosh Kumar T */ public class SSLTransport extends Debuggable implements Transport{ private Transport transport; private final SSLEngine engine; private final ByteBuffer dummy = ByteBuffer.allocate(0); private final ByteBuffer appReadBuffer; // ready for app.read private ByteBuffer appWriteBuffer; // ready for app.write private final ByteBuffer netReadBuffer; // ready for engine.unwrap private final ByteBuffer netWriteBuffer; // ready for channel.write private boolean initialHandshake = true; private SSLEngineResult.HandshakeStatus hsStatus; private SSLEngineResult.Status status = null; private HandshakeCompletedListener handshakeCompletedListener; public SSLTransport(Transport transport, SSLEngine engine, HandshakeCompletedListener handshakeCompletedListener) throws IOException{ this.transport = transport; this.engine = engine; this.handshakeCompletedListener = handshakeCompletedListener; SSLSession session = engine.getSession(); appReadBuffer = ByteBuffer.allocate(session.getApplicationBufferSize()); appReadBuffer.position(appReadBuffer.limit()); appWriteBuffer = dummy; netReadBuffer = ByteBuffer.allocate(session.getPacketBufferSize()); netReadBuffer.position(netReadBuffer.limit()); netWriteBuffer = ByteBuffer.allocate(session.getPacketBufferSize()); netWriteBuffer.position(netWriteBuffer.limit()); start(); } @Override public long id(){ return -transport.id(); } @Override public void id(long newID){ transport.id(newID); } @Override public ClientChannel client(){ return transport.client(); } private void validate() throws IOException{ if(asyncException!=null) throw new IOException("ASYNC_EXCEPTION: "+asyncException.getMessage(), asyncException); if(appClosed) throw new ClosedChannelException(); } @Override public int read(ByteBuffer dst) throws IOException{ if(DEBUG) println("app@"+id()+".read{"); try{ int read = appRead(dst); if(DEBUG) println("return: "+read); return read; }finally{ if(DEBUG) println("}"); } } @Override public int write(ByteBuffer src) throws IOException{ if(DEBUG) println("app@"+id()+".write{"); try{ int wrote = appWrite(src); if(DEBUG) println("return: "+wrote); return wrote; }finally{ if(DEBUG) println("}"); } } private void start() throws IOException{ if(DEBUG) println("app@"+id()+".start{"); int ops = transport.interests(); boolean readWait = (ops&OP_READ)!=0; boolean writeWait = (ops&OP_WRITE)!=0; if(readWait) transport.removeInterest(OP_READ); if(writeWait) transport.removeInterest(OP_WRITE); engine.beginHandshake(); switch(hsStatus=engine.getHandshakeStatus()){ case NEED_UNWRAP: channelRead(); break; case NEED_WRAP: channelWrite(); break; default: assert false; } if(readWait) addInterest(OP_READ); if(writeWait) addInterest(OP_WRITE); if(DEBUG) println("}"); } private boolean run() throws IOException{ try{ while(true){ switch(hsStatus){ case NEED_TASK: processNeedTask(); continue; case NEED_WRAP: if(processWrap()) continue; return false; case NEED_UNWRAP: if(processUnwrap()) continue; return false; case FINISHED: if(handshakeCompletedListener!=null) handshakeCompletedListener.handshakeCompleted(new HandshakeCompletedEvent(client(), engine.getSession())); default: initialHandshake = false; return true; } } }finally{ if(engine.isInboundDone() && engine.isOutboundDone() && !netWriteBuffer.hasRemaining()) closeTransport(); } } private void processNeedTask(){ if(DEBUG) println("running tasks"); Runnable task; while((task=engine.getDelegatedTask())!=null) task.run(); hsStatus = engine.getHandshakeStatus(); } private boolean processWrap() throws IOException{ assert !netWriteBuffer.hasRemaining(); netWriteBuffer.clear(); SSLEngineResult result = engine.wrap(appWriteBuffer, netWriteBuffer); hsStatus = result.getHandshakeStatus(); status = result.getStatus(); netWriteBuffer.flip(); if(DEBUG){ println(String.format( "%-6s: %-16s %-15s %5d %5d", "wrap", status, hsStatus, result.bytesConsumed(), result.bytesProduced() )); } switch(status){ case BUFFER_OVERFLOW: // not enough room in netWriteBuffer case BUFFER_UNDERFLOW: // Nothing to wrap: no data was present in appWriteBuffer throw new ImpossibleException(); case OK: return flush(); case CLOSED: assert engine.isOutboundDone(); return flush(); } throw new ImpossibleException(); } private boolean flush() throws IOException{ if(netWriteBuffer.hasRemaining()){ transport.write(netWriteBuffer); if(netWriteBuffer.hasRemaining()){ waitForChannelWrite(); return false; } } if(engine.isOutboundDone()){ assert (transport.interests() & OP_WRITE)==0; try{ transport.shutdownOutput(); }catch(IOException ex){ // ignore } } return true; } private boolean processUnwrap() throws IOException{ assert !appReadBuffer.hasRemaining(); if(!netReadBuffer.hasRemaining()){ waitForChannelRead(); return false; } appReadBuffer.clear(); SSLEngineResult result = engine.unwrap(netReadBuffer, appReadBuffer); appReadBuffer.flip(); hsStatus = result.getHandshakeStatus(); status = result.getStatus(); if(DEBUG){ println(String.format( "%-6s: %-16s %-15s %5d %5d", "unwrap", result.getStatus(), result.getHandshakeStatus(), result.bytesConsumed(), result.bytesProduced() )); } switch(status){ case BUFFER_OVERFLOW: // not enough room in appReadBuffer throw new ImpossibleException(); case BUFFER_UNDERFLOW: // not enough data in netReadBuffer waitForChannelRead(); return false; case OK: if(appReadBuffer.hasRemaining()){ if(appClosed){ if(DEBUG) println("discarding data in appReadBuffer@"+id()); appReadBuffer.position(appReadBuffer.limit()); return true; } if(appReadWait) enableAppRead(); return false; }else return true; case CLOSED: assert engine.isInboundDone(); try{ client().realChannel().socket().shutdownInput(); }catch(IOException ex){ if(!client().realChannel().socket().isInputShutdown()) throw ex; } if(appReadWait) enableAppRead(); return false; } throw new ImpossibleException(); } private boolean channelReadWait = false; private void waitForChannelRead() throws IOException{ if(!channelReadWait){ channelReadWait = true; transport.addInterest(OP_READ); } } private boolean channelWriteWait = false; private void waitForChannelWrite() throws IOException{ if(!channelWriteWait){ channelWriteWait = true; transport.addInterest(OP_WRITE); } } private boolean appReadWait = false; private void waitForAppRead() throws IOException{ if(!appReadWait){ appReadWait = true; if(DEBUG) println("app@" + id() + ".readWait"); if(engine.isInboundDone()) enableAppRead(); else if(!initialHandshake){ if(appReadBuffer.hasRemaining()) enableAppRead(); else channelRead(); } } } private boolean appWriteWait = false; private void waitForAppWrite() throws IOException{ if(!appWriteWait){ if(outputShutdown) throw new IOException("output is shutdown for app@"+id()); appWriteWait = true; if(DEBUG) println("app@"+id()+".writeWait"); if(!initialHandshake){ if(!appWriteBuffer.hasRemaining()) enableAppWrite(); } } } @Override public int interests(){ int ops = 0; if(appReadWait) ops |= OP_READ; if(appWriteWait) ops |= OP_WRITE; return ops; } @Override public void addInterest(int interest) throws IOException{ if(DEBUG) println("app@"+id()+".register{"); validate(); if(interest==OP_READ) waitForAppRead(); if(interest==OP_WRITE) waitForAppWrite(); if(isAppReady()) client().nioSelector.ready.add(client()); if(DEBUG) println("}"); } @Override public void removeInterest(int operation) throws IOException{ validate(); throw new UnsupportedOperationException(); } private boolean appReadReady = false; private void enableAppRead(){ if(DEBUG) println("app@"+id()+".readReady"); appReadReady = true; } private boolean appWriteReady = false; private void enableAppWrite(){ if(DEBUG) println("app@"+id()+".writeReady"); appWriteReady = true; } private void notifyAppWrite() throws IOException{ if(appWriteWait) enableAppWrite(); else if(outputShutdown && !engine.isOutboundDone()) closeOutbound(); } @Override public int ready(){ int ops = 0; if(appReadReady) ops |= OP_READ; if(appWriteReady) ops |= OP_WRITE; return ops; } private boolean isAppReady(){ if(appReadReady) appReadWait = false; if(appWriteReady) appWriteWait = false; return !appClosed && (appReadReady || appWriteReady); } private void channelRead() throws IOException{ while(true){ netReadBuffer.compact(); int read = status==BUFFER_UNDERFLOW ? 0 : netReadBuffer.position(); read += transport.read(netReadBuffer); netReadBuffer.flip(); if(read==0) waitForChannelRead(); else if(read==-1){ try{ engine.closeInbound(); }catch(SSLException ex){ // peer's close_notify is not received yet } if(appReadWait) enableAppRead(); }else{ hsStatus = NEED_UNWRAP; if(run()){ notifyAppWrite(); if(appReadWait){ if(appReadBuffer.hasRemaining()) enableAppRead(); else{ continue; } } } } break; } } private void channelWrite() throws IOException{ if(flush()){ if(run()){ notifyAppWrite(); if(appReadWait){ if(appReadBuffer.hasRemaining()) enableAppRead(); } } } } private int appRead(ByteBuffer dst) throws IOException{ validate(); appReadReady = false; if(appReadBuffer.hasRemaining()){ int limit = Math.min(appReadBuffer.remaining(), dst.remaining()); if(dst.hasArray()){ System.arraycopy(appReadBuffer.array(), appReadBuffer.position(), dst.array(), dst.position(), limit); appReadBuffer.position(appReadBuffer.position()+limit); dst.position(dst.position()+limit); }else{ for(int i=0; i<limit; i++) dst.put(appReadBuffer.get()); } return limit; }else return engine.isInboundDone() ? -1 : 0; } private int appWrite(ByteBuffer dst) throws IOException{ validate(); appWriteReady = false; if(initialHandshake || outputShutdown || netWriteBuffer.hasRemaining()) return 0; int pos = dst.position(); appWriteBuffer = dst; try{ hsStatus = NEED_WRAP; run(); return dst.position()-pos; }finally{ appWriteBuffer = dummy; } } private IOException asyncException; @Override public boolean process(){ if(DEBUG) println("app@"+id()+".process{"); try{ int ops = transport.interests(); boolean readReady = (ops&OP_READ)!=0; boolean writeReady = (ops&OP_WRITE)!=0; if(readReady){ channelReadWait = false; transport.removeInterest(OP_READ); } if(writeReady){ channelWriteWait = false; transport.removeInterest(OP_WRITE); } if(readReady) channelRead(); if(transport.isOpen() && writeReady) // to check key validity channelWrite(); if(engine.isInboundDone() && engine.isOutboundDone() && !netWriteBuffer.hasRemaining()) closeTransport(); }catch(IOException ex){ if(DEBUG) println("Async Exception: "+ex.getMessage()); if(appClosed) closeTransport(); else{ asyncException = ex; if(appReadWait) enableAppRead(); if(appWriteWait) enableAppWrite(); } } if(DEBUG) println("}"); return isAppReady(); } private boolean outputShutdown; @Override public void shutdownOutput() throws IOException{ if(DEBUG) println("app@"+id()+".shutdownOutput{"); outputShutdown = true; appWriteWait = appWriteReady = false; if(!netWriteBuffer.hasRemaining() && (engine.isInboundDone() || hsStatus==FINISHED || hsStatus==NOT_HANDSHAKING)) closeOutbound(); if(DEBUG) println("}"); } private void closeOutbound() throws IOException{ if(DEBUG) println("app@"+id()+".closeOutbound"); engine.closeOutbound(); hsStatus = NEED_WRAP; channelWrite(); } @Override public boolean isOutputShutdown(){ return outputShutdown; } private boolean appClosed; @Override public boolean isOpen(){ return !appClosed; } @Override public void close() throws IOException{ if(!appClosed){ asyncException = null; appClosed = true; if(DEBUG) println("app@"+id()+".close{"); if(appReadBuffer.hasRemaining()){ appReadBuffer.position(appReadBuffer.limit()); if(DEBUG) println("discarding data in appReadBuffer@"+id()); } if(!outputShutdown) shutdownOutput(); if(DEBUG) println("}"); } } private void closeTransport(){ try{ transport.close(); }catch(IOException ignore){ // ignore } } }
package org.openqa.selenium.chrome; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.DriverCommand; import org.openqa.selenium.remote.RemoteWebDriver; public class ChromeDriver extends RemoteWebDriver implements TakesScreenshot { /** * Creates a new ChromeDriver using the * {@link ChromeDriverService#createDefaultService default} server * configuration. */ public ChromeDriver() { this(ChromeDriverService.createDefaultService()); } /** * Creates a new ChromeDriver instance. The {@code service} will be started * along with the driver, and shutdown upon calling {@link #quit()}. * * @param service The service to use. */ public ChromeDriver(ChromeDriverService service) { super(new ChromeCommandExecutor(service), DesiredCapabilities.chrome()); } public <X> X getScreenshotAs(OutputType<X> target) { // Get the screenshot as base64. String base64 = execute(DriverCommand.SCREENSHOT).getValue().toString(); // ... and convert it. return target.convertFromBase64Png(base64); } }
package com.codingchili.core; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import com.codingchili.core.context.CoreContext; import com.codingchili.core.context.Delay; import com.codingchili.core.context.LaunchContext; import com.codingchili.core.listener.*; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.Timeout; import io.vertx.ext.unit.junit.VertxUnitRunner; import static com.codingchili.core.files.Configurations.system; /** * @author Robin Duda * <p> * Tests for the launcher. */ @RunWith(VertxUnitRunner.class) public class LauncherIT { private static TestContext test; private static Async async; private LaunchContext context; @Before public void setUp() { Delay.initialize(context); } @Rule public Timeout timeout = new Timeout(15, TimeUnit.SECONDS); @After public void tearDown(TestContext test) { if (context != null) context.vertx().close(test.asyncAssertSuccess()); } @Test public void testFailNotVerticle(TestContext test) { launchWithFail(NotClusterNode.class.getName(), test.async()); } @Test public void testFailNotFound(TestContext test) { launchWithFail("com.codingchili.core.Missing$1", test.async()); } @Test public void testMetricsEnabled(TestContext test) { async = test.async(); system().setMetrics(true); onStart = (vx) -> test.assertTrue(vx.isMetricsEnabled()); launchWithSuccess(TestService.class); } @Test public void testMetricsDisabled(TestContext test) { async = test.async(); system().setMetrics(false); onStart = (vx) -> test.assertFalse(vx.isMetricsEnabled()); launchWithSuccess(TestService.class); } @Test public void testDeployHandler(TestContext test) { LauncherIT.test = test; async = test.async(system().getHandlers()); launchWithSuccess(TestHandler.class); } @Test public void testDeployListener(TestContext test) { LauncherIT.test = test; async = test.async(system().getListeners()); launchWithSuccess(TestListener.class); } @Test public void testDeployAService(TestContext test) { LauncherIT.test = test; async = test.async(system().getServices()); launchWithSuccess(TestService.class); } @Test public void testDeployVerticle(TestContext test) { async = test.async(system().getHandlers()); launchWithSuccess(TestNodeVerticle.class); } public void launchWithSuccess(Class klass) { new Launcher(getLaunchContextFor(klass.getName())); } public void launchWithFail(Class klass, Async async) { launchWithFail(klass.getName(), async); } public void launchWithFail(String klass, Async async) { new Launcher(getLaunchContextFor(klass)) { @Override void exit() { async.complete(); } }; } public LaunchContext getLaunchContextFor(String node) { context = new LaunchContext(new String[]{}) { @Override protected List<String> block(String block) { List<String> list = new ArrayList<>(); list.add(node); return list; } }; return context; } private static Consumer<Vertx> onStart = (vx) -> { }; /** * Testnode that calls async-complete on deploy. */ public static class TestService implements CoreService { private CoreContext core; @Override public void init(CoreContext core) { this.core = core; } @Override public void stop(Future<Void> stop) { core.timer(500, handler -> { System.err.println("Service has been shut down"); stop.complete(); }); } @Override public void start(Future<Void> start) { test.assertNotNull(core); onStart.accept(core.vertx()); async.complete(); start.complete(); } } public static class TestHandler implements CoreHandler { public TestHandler() { async.countDown(); } @Override public void handle(Request request) { } @Override public String address() { return ""; } } public static class TestListener implements CoreListener { private ListenerSettings settings; private CoreContext core; private CoreHandler handler; @Override public void init(CoreContext core) { this.core = core; } @Override public CoreListener settings(Supplier<ListenerSettings> settings) { this.settings = settings.get(); return this; } @Override public CoreListener handler(CoreHandler handler) { this.handler = handler; return this; } @Override public void start(Future<Void> start) { test.assertNotNull(settings); test.assertNotNull(core); test.assertNotNull(handler); async.countDown(); start.complete(); } @Override public void stop(Future<Void> stop) { stop.complete(); } } /** * Testnode that calls async-complete on deploy. */ public static class TestNodeVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { async.countDown(); onStart.accept(vertx); future.complete(); } } /** * Test class that is not a cluster node and will fail to deploy. */ private static class NotClusterNode { } }
package org.newdawn.slick.tiled; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; import org.newdawn.slick.SlickException; import org.newdawn.slick.util.Log; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A layer of tiles on the map * * @author kevin * @author liamzebedee */ public class Layer { /** The code used to decode Base64 encoding */ private static byte[] baseCodes = new byte[256]; /** * Static initialiser for the codes created against Base64 */ static { for (int i = 0; i < 256; i++) baseCodes[i] = -1; for (int i = 'A'; i <= 'Z'; i++) baseCodes[i] = (byte) (i - 'A'); for (int i = 'a'; i <= 'z'; i++) baseCodes[i] = (byte) (26 + i - 'a'); for (int i = '0'; i <= '9'; i++) baseCodes[i] = (byte) (52 + i - '0'); baseCodes['+'] = 62; baseCodes['/'] = 63; } /** The map this layer belongs to */ private final TiledMap map; /** The index of this layer */ public int index; /** The name of this layer - read from the XML */ public String name; /** * The tile data representing this data, index 0 = tileset, index 1 = tile * id */ public int[][][] data; /** The width of this layer */ public int width; /** The height of this layer */ public int height; /** The opacity of this layer (range 0 to 1) */ public float opacity = 1; /** The visibility of this layer */ public boolean visible = true; /** the properties of this layer */ public Properties props; /** The TiledMapPlus of this layer */ private TiledMapPlus tmap; /** * Create a new layer based on the XML definition * * @param element * The XML element describing the layer * @param map * The map this layer is part of * @throws SlickException * Indicates a failure to parse the XML layer */ public Layer(TiledMap map, Element element) throws SlickException { this.map = map; if (map instanceof TiledMapPlus) { tmap = (TiledMapPlus) map; } name = element.getAttribute("name"); width = Integer.parseInt(element.getAttribute("width")); height = Integer.parseInt(element.getAttribute("height")); data = new int[width][height][3]; String opacityS = element.getAttribute("opacity"); if (!opacityS.equals("")) { opacity = Float.parseFloat(opacityS); } // now read the layer properties Element propsElement = (Element) element.getElementsByTagName( "properties").item(0); props = new Properties(); if (propsElement != null) { NodeList properties = propsElement.getElementsByTagName("property"); if (properties != null) { for (int p = 0; p < properties.getLength(); p++) { Element propElement = (Element) properties.item(p); String name = propElement.getAttribute("name"); String value = propElement.getAttribute("value"); props.setProperty(name, value); if ("0".equals(props.getProperty("visible"))) { visible = false; } } } } Element dataNode = (Element) element.getElementsByTagName("data").item( 0); String encoding = dataNode.getAttribute("encoding"); String compression = dataNode.getAttribute("compression"); if (encoding.equals("base64") && compression.equals("gzip")) { try { Node cdata = dataNode.getFirstChild(); char[] enc = cdata.getNodeValue().trim().toCharArray(); byte[] dec = decodeBase64(enc); GZIPInputStream is = new GZIPInputStream( new ByteArrayInputStream(dec)); readData(is); } catch (IOException e) { Log.error(e); throw new SlickException("Unable to decode base 64 block"); } } else if (encoding.equals("base64") && compression.equals("zlib")) { Node cdata = dataNode.getFirstChild(); char[] enc = cdata.getNodeValue().trim().toCharArray(); byte[] dec = decodeBase64(enc); InflaterInputStream is = new InflaterInputStream( new ByteArrayInputStream(dec)); readData(is); } else { throw new SlickException("Unsupport tiled map type: " + encoding + "," + compression + " (only gzip/zlib base64 supported)"); } } /** * For reading decompressed, decoded Layer data into this layer * * @param is */ protected void readData(InputStream is) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int tileId = 0; try { tileId |= is.read(); tileId |= is.read() << 8; tileId |= is.read() << 16; tileId |= is.read() << 24; } catch (Exception e) { e.printStackTrace(); } if (tileId == 0) { data[x][y][0] = -1; data[x][y][1] = 0; data[x][y][2] = 0; } else { int realTileId = tileId & 0x1FFFFFFF; TileSet set = map.findTileSet(realTileId); if (set != null) { data[x][y][0] = set.index; data[x][y][1] = realTileId - set.firstGID; } data[x][y][2] = tileId; } } } } /** * Get the gloal ID of the tile at the specified location in this layer * * @param x * The x coorindate of the tile * @param y * The y coorindate of the tile * @return The global ID of the tile */ public int getTileID(int x, int y) { return data[x][y][2]; } /** * Set the global tile ID at a specified location * * @param x * The x location to set * @param y * The y location to set * @param tile * The tile value to set */ public void setTileID(int x, int y, int tile) { if (tile == 0) { data[x][y][0] = -1; data[x][y][1] = 0; data[x][y][2] = 0; } else { TileSet set = map.findTileSet(tile); data[x][y][0] = set.index; // tileSetIndex data[x][y][1] = tile - set.firstGID; // localID data[x][y][2] = tile; // globalID } } /** * Render a section of this layer * * @param x * The x location to render at * @param y * The y location to render at * @param sx * The x tile location to start rendering * @param sy * The y tile location to start rendering * @param width * The number of tiles across to render * @param ty * The line of tiles to render * @param lineByLine * True if we should render line by line, i.e. giving us a chance * to render something else between lines * @param mapTileWidth * the tile width specified in the map file * @param mapTileHeight * the tile height specified in the map file */ public void render(int x, int y, int sx, int sy, int width, int ty, boolean lineByLine, int mapTileWidth, int mapTileHeight) { for (int tileset = 0; tileset < map.getTileSetCount(); tileset++) { TileSet set = null; for (int tx = 0; tx < width; tx++) { if ((sx + tx < 0) || (sy + ty < 0)) { continue; } if ((sx + tx >= this.width) || (sy + ty >= this.height)) { continue; } if (data[sx + tx][sy + ty][0] == tileset) { if (set == null) { set = map.getTileSet(tileset); set.tiles.startUse(); } int sheetX = set.getTileX(data[sx + tx][sy + ty][1]); int sheetY = set.getTileY(data[sx + tx][sy + ty][1]); int tileOffsetY = set.tileHeight - mapTileHeight; // TODO CHECK // LSB: Rotate // LSB+1: Flip Y // LSB+2: Flip X byte b = (byte) ((data[sx + tx][sy + ty][2] & 0xE0000000L) >> 29); set.tiles.setAlpha(this.opacity); // Sets opacity/alpha value set.tiles.renderInUse(x + (tx * mapTileWidth), y + (ty * mapTileHeight) - tileOffsetY, sheetX, sheetY, b); } } if (lineByLine) { if (set != null) { set.tiles.endUse(); set = null; } map.renderedLine(ty, ty + sy, index); } if (set != null) { set.tiles.endUse(); } } } /** * Decode a Base64 string as encoded by TilED * * @param data * The string of character to decode * @return The byte array represented by character encoding */ private byte[] decodeBase64(char[] data) { int temp = data.length; for (int ix = 0; ix < data.length; ix++) { if ((data[ix] > 255) || baseCodes[data[ix]] < 0) { --temp; } } int len = (temp / 4) * 3; if ((temp % 4) == 3) len += 2; if ((temp % 4) == 2) len += 1; byte[] out = new byte[len]; int shift = 0; int accum = 0; int index = 0; for (int ix = 0; ix < data.length; ix++) { int value = (data[ix] > 255) ? -1 : baseCodes[data[ix]]; if (value >= 0) { accum <<= 6; shift += 6; accum |= value; if (shift >= 8) { shift -= 8; out[index++] = (byte) ((accum >> shift) & 0xff); } } } if (index != out.length) { throw new RuntimeException( "Data length appears to be wrong (wrote " + index + " should be " + out.length + ")"); } return out; } /** * Gets all Tiles from this layer, formatted into Tile objects Can only be * used if the layer was loaded using TiledMapPlus * * @author liamzebedee * @throws SlickException */ public ArrayList<Tile> getTiles() throws SlickException { if (tmap == null) { throw new SlickException( "This method can only be used with Layers loaded using TiledMapPlus"); } ArrayList<Tile> tiles = new ArrayList<Tile>(); for (int x = 0; x < this.width; x++) { for (int y = 0; y < this.height; y++) { if (this.data[x][y][0] != -1) { String tilesetName = tmap.tileSets.get(this.data[x][y][0]).name; Tile t = new Tile(x, y, this.name, y, tilesetName); tiles.add(t); } } } return tiles; } /** * Get all tiles from this layer that are part of a tileset Can only be used * if the layer was loaded using TiledMapPlus * * @author liamzebedee * @param tilesetName * The name of the tileset that the tiles are part of * @throws SlickException */ public ArrayList<Tile> getTilesOfTileset(String tilesetName) throws SlickException { if (tmap == null) { throw new SlickException( "This method can only be used with Layers loaded using TiledMapPlus"); } ArrayList<Tile> tiles = new ArrayList<Tile>(); int tilesetID = tmap.getTilesetID(tilesetName); for (int x = 0; x < tmap.getWidth(); x++) { for (int y = 0; y < tmap.getHeight(); y++) { if (this.data[x][y][0] == tilesetID) { Tile t = new Tile(x, y, this.name, this.data[x][y][1], tilesetName); tiles.add(t); } } } return tiles; } /** * Removes a tile * * @author liamzebedee * @param x * Tile X * @param y * Tile Y */ public void removeTile(int x, int y) { this.data[x][y][0] = -1; } /** * Sets a tile's tileSet Can only be used if the layer was loaded using * TiledMapPlus * * @author liamzebedee * @param x * Tile X * @param y * Tile Y * @param tileOffset * The offset of the tile, within the tileSet to set this tile * to, ordered in rows * @param tilesetName * The name of the tileset to set the tile to * @throws SlickException */ public void setTile(int x, int y, int tileOffset, String tilesetName) throws SlickException { if (tmap == null) { throw new SlickException( "This method can only be used with Layers loaded using TiledMapPlus"); } int tilesetID = tmap.getTilesetID(tilesetName); TileSet tileset = tmap.getTileSet(tilesetID); this.data[x][y][0] = tileset.index; // tileSetIndex this.data[x][y][1] = tileOffset; // localID this.data[x][y][2] = tileset.firstGID + tileOffset; // globalID } /** * Returns true if this tile is part of that tileset Can only be used if the * layer was loaded using TiledMapPlus * * @author liamzebedee * @param x * The x co-ordinate of the tile * @param y * The y co-ordinate of the tile * @param tilesetName * The name of the tileset, to check if the tile is part of * @throws SlickException */ public boolean isTileOfTileset(int x, int y, String tilesetName) throws SlickException { if (tmap == null) { throw new SlickException( "This method can only be used with Layers loaded using TiledMapPlus"); } int tilesetID = tmap.getTilesetID(tilesetName); if (this.data[x][y][0] == tilesetID) { return true; } return false; } @Override public String toString() { return "Layer [name=" + name + ", width=" + width + ", height=" + height + ", opacity=" + opacity + ", visible=" + visible + ", props=" + props + "]"; } public int getLocalTileId(int x, int y) { return data[x][y][1]; } }
package mil.nga.giat.mage.sdk.preferences; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import com.google.common.base.Predicate; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import mil.nga.giat.mage.sdk.R; import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility; import mil.nga.giat.mage.sdk.http.resource.ApiResource; /** * Loads the default configuration from the local property files, and also loads * the server configuration. * * @author wiedemanns * */ public class PreferenceHelper implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String LOG_NAME = PreferenceHelper.class.getName(); private PreferenceHelper() { } private static PreferenceHelper preferenceHelper; private static Context mContext; public static PreferenceHelper getInstance(final Context context) { if (context == null) { return null; } mContext = context; if (preferenceHelper == null) { preferenceHelper = new PreferenceHelper(); } return preferenceHelper; } /** * Should probably be called only once to initialize the settings and * properties. * */ public synchronized void initialize(Boolean forceReinitialize, final Class<?>... xmlClasses) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); // TODO preserve the server url. // We really should have seperate preference files for each user. Server url will be part // of the 'global' preferences and not cleared when a different user logs in String oldServerURL = PreferenceManager.getDefaultSharedPreferences(mContext).getString(mContext.getString(R.string.serverURLKey), mContext.getString(R.string.serverURLDefaultValue)); String oldBuildVersion = sharedPreferences.getString(mContext.getString(R.string.buildVersionKey), null); String newBuildVersion = null; try { newBuildVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName; } catch (NameNotFoundException nnfe) { Log.e(LOG_NAME , "Problem retrieving build version.", nnfe); } if(!StringUtils.isBlank(oldBuildVersion) && !StringUtils.isBlank(newBuildVersion)) { String oldMajorVersion = oldBuildVersion.split("\\.")[0]; String newMajorVersion = newBuildVersion.split("\\.")[0]; if(!oldMajorVersion.equals(newMajorVersion)) { forceReinitialize = true; } } if (forceReinitialize) { sharedPreferences.edit().clear().commit(); } Set<Integer> resourcesToLoad = new LinkedHashSet<>(); for (Class xmlClass : xmlClasses) { for (Field field : xmlClass.getDeclaredFields()) { if (field.getName().endsWith("preference")) { try { resourcesToLoad.add(field.getInt(new R.xml())); } catch (Exception e) { Log.e(LOG_NAME, "Error loading preference file", e); } } } } // load preferences from mdk xml files first initializeLocal(resourcesToLoad.toArray((new Integer[resourcesToLoad.size()]))); // add programmatic preferences Editor editor = sharedPreferences.edit(); if (!StringUtils.isBlank(newBuildVersion)) { editor.putString(mContext.getString(R.string.buildVersionKey), newBuildVersion).commit(); } // add back in the server url editor.putString(mContext.getString(R.string.serverURLKey), oldServerURL).commit(); logKeyValuePairs(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } public void logKeyValuePairs() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); // log all preference values for(Map.Entry<String, ?> e : sharedPreferences.getAll().entrySet()) { String key = e.getKey(); Object value = e.getValue(); String valueType = (value == null) ? null : value.getClass().getName(); Log.d(LOG_NAME, "SharedPreferences contains (key, value, type): (" + String.valueOf(key) + ", " + String.valueOf(value) + ", " + String.valueOf(valueType) + ")"); } } public boolean containsLocalAuthentication() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); for (String key : sharedPreferences.getAll().keySet()) { if (key.startsWith("gAuthenticationStrategiesLocal")) { return true; } } return false; } public boolean containsGoogleAuthentication() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); for (String key : sharedPreferences.getAll().keySet()) { if (key.startsWith("gAuthenticationStrategiesGoogle")) { return true; } } return false; } private synchronized void initializeLocal(Integer... xmlFiles) { for (int id : xmlFiles) { Log.d(LOG_NAME, "Loading resources from: " + mContext.getResources().getResourceEntryName(id)); PreferenceManager.setDefaultValues(mContext, id, true); } } public synchronized void readRemoteApi(String url, Predicate<Exception> callback) { new RemotePreferenceColonizationApi(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url); } public void validateServerApi(final String url, final Predicate<Exception> callback) { try { final URL serverURL = new URL(url); // make sure you can get to the host! ConnectivityUtility.isResolvable(serverURL.getHost(), new Predicate<Exception>() { @Override public boolean apply(Exception e) { if (e == null) { PreferenceHelper.getInstance(mContext).readRemoteApi(url, new Predicate<Exception>() { public boolean apply(Exception e) { if (e != null) { return callback.apply(new Exception("No server information")); } else { // check versions SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); Integer compatibleMajorVersion = sharedPreferences.getInt(mContext.getString(R.string.compatibleVersionMajorKey), mContext.getResources().getInteger(R.integer.compatibleVersionMajorDefaultValue)); Integer compatibleMinorVersion = sharedPreferences.getInt(mContext.getString(R.string.compatibleVersionMinorKey), mContext.getResources().getInteger(R.integer.compatibleVersionMinorDefaultValue)); boolean hasServerMajorVersion = sharedPreferences.contains(mContext.getString(R.string.serverVersionMajorKey)); boolean hasServerMinorVersion = sharedPreferences.contains(mContext.getString(R.string.serverVersionMinorKey)); if (!hasServerMajorVersion || !hasServerMinorVersion) { return callback.apply(new Exception("No server version")); } else { int serverMajorVersion = sharedPreferences.getInt(mContext.getString(R.string.serverVersionMajorKey), 0); int serverMinorVersion = sharedPreferences.getInt(mContext.getString(R.string.serverVersionMinorKey), 0); Log.d(LOG_NAME, "server major version: " + serverMajorVersion); Log.d(LOG_NAME, "server minor version: " + serverMinorVersion); Log.d(LOG_NAME, "compatibleMajorVersion: " + compatibleMajorVersion); Log.d(LOG_NAME, "compatibleMinorVersion: " + compatibleMinorVersion); if (!compatibleMajorVersion.equals(serverMajorVersion)) { return callback.apply(new Exception("This app is not compatible with this server")); } else if (compatibleMinorVersion > serverMinorVersion) { return callback.apply(new Exception("This app is not compatible with this server")); } else { return callback.apply(null); } } } } }); } else { return callback.apply(new Exception("Host does not resolve")); } return true; } }); } catch (MalformedURLException mue) { callback.apply(new Exception("Bad URL")); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Map<String, ?> sharedPreferenceMap = sharedPreferences.getAll(); Object value = sharedPreferenceMap.get(key); String valueType = (value == null) ? null : value.getClass().getName(); Log.d(LOG_NAME, "SharedPreferences changed. Now contains (key, value, type): (" + String.valueOf(key) + ", " + String.valueOf(value) + ", " + String.valueOf(valueType) + ")"); } private class RemotePreferenceColonizationApi extends AsyncTask<String, Void, Exception> { private Predicate<Exception> callback = null; public RemotePreferenceColonizationApi (Predicate<Exception> callback) { this.callback = callback; } @Override protected Exception doInBackground(String... params) { String url = params[0]; return initializeApi(url); } @Override protected void onPostExecute(Exception e) { super.onPostExecute(e); if(callback != null) { callback.apply(e); } } /** * Flattens the json from the server and puts key, value pairs in the DefaultSharedPreferences * * @param sharedPreferenceName preference name * @param json json value */ private void populateValues(String sharedPreferenceName, JSONObject json) { @SuppressWarnings("unchecked") Iterator<String> iter = json.keys(); while (iter.hasNext()) { String key = iter.next(); try { Object value = json.get(key); if (value instanceof JSONObject) { populateValues(sharedPreferenceName + Character.toUpperCase(key.charAt(0)) + ((key.length() > 1) ? key.substring(1) : ""), (JSONObject) value); } else { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); Editor editor = sharedPreferences.edit(); String keyString = sharedPreferenceName + Character.toUpperCase(key.charAt(0)) + ((key.length() > 1) ? key.substring(1) : ""); Log.i(LOG_NAME, keyString + " is " + String.valueOf(sharedPreferences.getAll().get(keyString)) + ". Setting it to " + String.valueOf(value) + "."); if(value instanceof Number) { if(value instanceof Long) { editor.putLong(keyString, (Long)value); } else if(value instanceof Float) { editor.putFloat(keyString, (Float)value); } else if(value instanceof Double) { editor.putFloat(keyString, ((Double)value).floatValue()); } else if(value instanceof Integer) { editor.putInt(keyString, (Integer)value).commit(); } else if(value instanceof Short) { editor.putInt(keyString, ((Short)value).intValue()); } else { Log.e(LOG_NAME, keyString + " with value " + String.valueOf(value) + " is not of valid number type. Skipping this key-value pair."); } } else if(value instanceof Boolean) { editor.putBoolean(keyString, (Boolean)value).commit(); } else if(value instanceof String) { editor.putString(keyString, (String)value).commit(); } else if(value instanceof Character) { editor.putString(keyString, Character.toString((Character)value)); } else { // don't know what type this is, just use toString try { editor.putString(keyString, value.toString()); } catch(Exception e) { Log.e(LOG_NAME, keyString + " with value " + String.valueOf(value) + " is not of valid type. Skipping this key-value pair."); } } editor.commit(); } } catch (JSONException je) { je.printStackTrace(); } } } private void removeValues(String sharedPreferenceName) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = sharedPreferences.edit(); for (String key : sharedPreferences.getAll().keySet()) { if (key.startsWith(sharedPreferenceName)) { editor.remove(key); } } editor.commit(); } private Exception initializeApi(String url) { ApiResource apiResource = new ApiResource(mContext); try { String api = apiResource.getApi(url); JSONObject apiJson = new JSONObject(api); removeValues("g"); populateValues("g", apiJson); } catch (Exception e) { Log.e(LOG_NAME, "Problem reading server api settings: " + url, e); return e; } return null; } } }
package com.yahoo.squidb.data; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.text.TextUtils; import android.util.Log; import com.yahoo.squidb.Beta; import com.yahoo.squidb.data.adapter.DefaultOpenHelperWrapper; import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper; import com.yahoo.squidb.data.adapter.SQLiteOpenHelperWrapper; import com.yahoo.squidb.data.adapter.SquidTransactionListener; import com.yahoo.squidb.sql.CompiledStatement; import com.yahoo.squidb.sql.Criterion; import com.yahoo.squidb.sql.Delete; import com.yahoo.squidb.sql.Field; import com.yahoo.squidb.sql.Index; import com.yahoo.squidb.sql.Insert; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Property.PropertyVisitor; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.sql.SqlStatement; import com.yahoo.squidb.sql.SqlTable; import com.yahoo.squidb.sql.Table; import com.yahoo.squidb.sql.TableStatement; import com.yahoo.squidb.sql.Update; import com.yahoo.squidb.sql.View; import com.yahoo.squidb.sql.VirtualTable; import com.yahoo.squidb.utility.VersionCode; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * SquidDatabase is a database abstraction which wraps a SQLite database. * <p> * Use this class to control the lifecycle of your database where you would normally use a * {@link android.database.sqlite.SQLiteOpenHelper}. The first call to a read or write operation will open the database. * You can close it again using {@link #close()}. * <p> * SquidDatabase provides typesafe reads and writes using model classes. For example, rather than using rawQuery to * get a Cursor, use {@link #query(Class, Query)}. * <p> * By convention, methods beginning with "try" (e.g. {@link #tryCreateTable(Table) tryCreateTable}) return true * if the operation succeeded and false if it failed for any reason. If it fails, there will also be a call to * {@link #onError(String, Throwable) onError}. * <p> * Methods that use String arrays for where clause arguments ({@link #update(String, ContentValues, String, String[]) * update}, {@link #updateWithOnConflict(String, ContentValues, String, String[], int) updateWithOnConflict}, and * {@link #delete(String, String, String[]) delete}) are wrappers around Android's {@link SQLiteDatabase} methods. * However, Android's default behavior of binding all arguments as strings can have unexpected bugs, particularly when * working with SQLite functions. For example: * * <pre> * select * from t where _id = '1'; // Returns the first row * select * from t where abs(_id) = '1'; // Always returns empty set * </pre> * * For this reason, these methods are protected rather than public. You can choose to expose them in your database * subclass if you wish, but we recommend that you instead use the typesafe, public, model-bases methods, such as * {@link #update(Criterion, TableModel)}, {@link #updateWithOnConflict(Criterion, TableModel, * TableStatement.ConflictAlgorithm)}, {@link #delete(Class, long)}, and {@link #deleteWhere(Class, Criterion)}. * <p> * As a convenience, when calling the {@link #query(Class, Query) query} and {@link #fetchByQuery(Class, Query) * fetchByQuery} methods, if the <code>query</code> argument does not have a FROM clause, the table or view to select * from will be inferred from the provided <code>modelClass</code> argument (if possible). This allows for invocations * where {@link Query#from(com.yahoo.squidb.sql.SqlTable) Query.from} is never explicitly called: * * <pre> * SquidCursor&lt;Person&gt; cursor = * db.query(Person.class, Query.select().orderBy(Person.NAME.asc())); * </pre> * * By convention, the <code>fetch...</code> methods return a single model instance corresponding to the first record * found, or null if no records are found for that particular form of fetch. * <p> * When implementing your own database access methods in your SquidDatabase subclass, you should not use the object's * monitor for locking (e.g. synchronized methods or synchronized(this) blocks) -- doing so may cause deadlocks under * certain conditions. Most users will not need to worry about this and will be able to implement things in * their SquidDatabase subclass without resorting to locking, as all SquidDatabase methods are thread-safe. If you * really do need locking for some reason, use a different object's monitor, or use {@link #acquireExclusiveLock()} or * {@link #acquireNonExclusiveLock()} to control access to the database connection itself. */ public abstract class SquidDatabase { /** * @return the database name */ public abstract String getName(); /** * @return the database version */ protected abstract int getVersion(); /** * @return all {@link Table Tables} and {@link VirtualTable VirtualTables} and that should be created when the * database is created */ protected abstract Table[] getTables(); /** * @return all {@link View Views} that should be created when the database is created. Views will be created after * all Tables have been created. */ protected View[] getViews() { return null; } /** * @return all {@link Index Indexes} that should be created when the database is created. Indexes will be created * after Tables and Views have been created. */ protected Index[] getIndexes() { return null; } /** * Called after the database has been created. At this time, all {@link Table Tables} and {@link * VirtualTable VirtualTables} returned from {@link #getTables()}, all {@link View Views} from {@link #getViews()}, * and all {@link Index Indexes} from {@link #getIndexes()} will have been created. Any additional database setup * should be done here, e.g. creating other views, indexes, triggers, or inserting data. * * @param db the {@link SQLiteDatabaseWrapper} being created */ protected void onTablesCreated(SQLiteDatabaseWrapper db) { } /** * Called when the database should be upgraded from one version to another. The most common pattern to use is a * fall-through switch statement with calls to the tryAdd/Create/Drop methods: * * <pre> * switch(oldVersion) { * case 1: * tryAddColumn(MyModel.NEW_COL_1); * case 2: * tryCreateTable(MyNewModel.TABLE); * </pre> * * @param db the {@link SQLiteDatabaseWrapper} being upgraded * @param oldVersion the current database version * @param newVersion the database version being upgraded to * @return true if the upgrade was handled successfully, false otherwise */ protected abstract boolean onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion); /** * Called when the database should be downgraded from one version to another * * @param db the {@link SQLiteDatabaseWrapper} being upgraded * @param oldVersion the current database version * @param newVersion the database version being downgraded to * @return true if the downgrade was handled successfully, false otherwise. The default implementation returns true. */ protected boolean onDowngrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { return true; } /** * Called to notify of a failure in {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade()} or * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade()}, either because it returned false or because * an unexpected exception occurred. Subclasses can take drastic corrective action here, e.g. recreating the * database with {@link #recreate()}. The default implementation throws an exception. * <p> * Note that taking no action here leaves the database in whatever state it was in when the error occurred, which * can result in unexpected errors if callers are allowed to invoke further operations on the database. * * @param failure details about the upgrade or downgrade that failed */ protected void onMigrationFailed(MigrationFailedException failure) { throw failure; } /** * Called when the database connection is being configured, to enable features such as write-ahead logging or * foreign key support. * * This method may be called at different points in the database lifecycle depending on the environment. When using * a custom SQLite build with the squidb-sqlite-bindings project, or when running on Android API >= 16, it is * called before {@link #onTablesCreated(SQLiteDatabaseWrapper) onTablesCreated}, * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade}, * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade}, * and {@link #onOpen(SQLiteDatabaseWrapper) onOpen}. If it is running on stock Android SQLite and API < 16, it * is called immediately before onOpen but after the other callbacks. The discrepancy is because onConfigure was * only introduced as a callback in API 16, but the ordering should not matter much for most use cases. * <p> * This method should only call methods that configure the parameters of the database connection, such as * {@link SQLiteDatabaseWrapper#enableWriteAheadLogging}, {@link SQLiteDatabaseWrapper#setForeignKeyConstraintsEnabled}, * {@link SQLiteDatabaseWrapper#setLocale}, {@link SQLiteDatabaseWrapper#setMaximumSize}, or executing PRAGMA statements. * * @param db the {@link SQLiteDatabaseWrapper} being configured */ protected void onConfigure(SQLiteDatabaseWrapper db) { } /** * Called when the database has been opened. This method is called after the database connection has been * configured and after the database schema has been created, upgraded, or downgraded as necessary. * * @param db the {@link SQLiteDatabaseWrapper} being opened */ protected void onOpen(SQLiteDatabaseWrapper db) { } /** * Called when an error occurs. This is primarily for clients to log notable errors, not for taking corrective * action on them. The default implementation prints a warning log. * * @param message an error message * @param error the error that was encountered */ protected void onError(String message, Throwable error) { Log.w(getClass().getSimpleName(), message, error); } private static final int STRING_BUILDER_INITIAL_CAPACITY = 128; private final Context context; private SquidDatabase attachedTo = null; private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); /** * SQLiteOpenHelperWrapper that takes care of database operations */ private SQLiteOpenHelperWrapper helper = null; /** * Internal pointer to open database. Hides the fact that there is a database and a wrapper by making a single * monolithic interface */ private SQLiteDatabaseWrapper database = null; /** * Cached version code */ private VersionCode sqliteVersion = null; /** * Map of class objects to corresponding tables */ private Map<Class<? extends AbstractModel>, SqlTable<?>> tableMap; private boolean isInMigration; private boolean isInMigrationFailedHook; /** * Create a new SquidDatabase * * @param context the Context, must not be null */ public SquidDatabase(Context context) { if (context == null) { throw new NullPointerException("Null context creating SquidDatabase"); } this.context = context.getApplicationContext(); initializeTableMap(); } private void initializeTableMap() { tableMap = new HashMap<Class<? extends AbstractModel>, SqlTable<?>>(); registerTableModels(getTables()); registerTableModels(getViews()); } private <T extends SqlTable<?>> void registerTableModels(T[] tables) { if (tables != null) { for (SqlTable<?> table : tables) { if (table.getModelClass() != null && !tableMap.containsKey(table.getModelClass())) { tableMap.put(table.getModelClass(), table); } } } } /** * @return the path to the underlying database file. */ public String getDatabasePath() { return context.getDatabasePath(getName()).getAbsolutePath(); } /** * Return the {@link SqlTable} corresponding to the specified model type * * @param modelClass the model class * @return the corresponding data source for the model. May be a table, view, or subquery * @throws UnsupportedOperationException if the model class is unknown to this database */ protected final SqlTable<?> getSqlTable(Class<? extends AbstractModel> modelClass) { Class<?> type = modelClass; SqlTable<?> table; //noinspection SuspiciousMethodCalls while ((table = tableMap.get(type)) == null && type != AbstractModel.class && type != Object.class) { type = type.getSuperclass(); } if (table != null) { return table; } throw new UnsupportedOperationException("Unknown model class " + modelClass); } /** * Return the {@link Table} corresponding to the specified TableModel class * * @param modelClass the model class * @return the corresponding table for the model * @throws UnsupportedOperationException if the model class is unknown to this database */ protected final Table getTable(Class<? extends TableModel> modelClass) { return (Table) getSqlTable(modelClass); } /** * Gets the underlying SQLiteDatabaseWrapper instance. Most users should not need to call this. If you call this * from your AbstractDatabase subclass with the intention of executing SQL, you should wrap the calls with a lock, * probably the non-exclusive one: * * <pre> * public void execSql(String sql) { * acquireNonExclusiveLock(); * try { * getDatabase().execSQL(sql); * } finally { * releaseNonExclusiveLock(); * } * } * </pre> * * You only need to acquire the exclusive lock if you truly need exclusive access to the database connection. * * @return the underlying {@link SQLiteDatabaseWrapper}, which will be opened if it is not yet opened * @see #acquireExclusiveLock() * @see #acquireNonExclusiveLock() */ protected synchronized final SQLiteDatabaseWrapper getDatabase() { // If we get here, we should already have the non-exclusive lock if (database == null) { openForWritingLocked(); } return database; } private void openForWritingLocked() { if (helper == null) { helper = getOpenHelper(context, getName(), new OpenHelperDelegate(), getVersion()); } boolean performRecreate = false; try { SQLiteDatabaseWrapper db = helper.openForWriting(); setDatabase(db); } catch (RecreateDuringMigrationException recreate) { performRecreate = true; } catch (MigrationFailedException fail) { onError(fail.getMessage(), fail); isInMigrationFailedHook = true; try { onMigrationFailed(fail); } finally { isInMigrationFailedHook = false; } } catch (RuntimeException e) { onError("Failed to open database: " + getName(), e); throw e; } if (performRecreate) { recreateLocked(); // OK to call this here, locks are already held } } @Beta @TargetApi(VERSION_CODES.JELLY_BEAN) public final String attachDatabase(SquidDatabase other) { if (attachedTo != null) { throw new IllegalStateException("Can't attach a database to a database that is itself attached"); } if (inTransaction()) { throw new IllegalStateException("Can't attach a database while in a transaction on the current thread"); } boolean walEnabled; acquireNonExclusiveLock(); try { walEnabled = (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) && getDatabase().isWriteAheadLoggingEnabled(); } finally { releaseNonExclusiveLock(); } if (walEnabled) { // need to wait for transactions to finish acquireExclusiveLock(); } try { return other.attachTo(this); } finally { if (walEnabled) { releaseExclusiveLock(); } } } /** * Detaches a database previously attached with {@link #attachDatabase(SquidDatabase)} * * @return true if the other database was successfully detached */ @Beta public final boolean detachDatabase(SquidDatabase other) { if (other.attachedTo != this) { throw new IllegalArgumentException("Database " + other.getName() + " is not attached to " + getName()); } return other.detachFrom(this); } private String attachTo(SquidDatabase attachTo) { if (attachedTo != null) { throw new IllegalArgumentException( "Database " + getName() + " is already attached to " + attachedTo.getName()); } if (inTransaction()) { throw new IllegalStateException( "Cannot attach database " + getName() + " to " + attachTo.getName() + " -- " + getName() + " is in a transaction on the calling thread"); } acquireExclusiveLock(); String attachedAs = getAttachedName(); if (!attachTo.tryExecSql("ATTACH '" + getDatabasePath() + "' AS '" + attachedAs + "'")) { releaseExclusiveLock(); // Failed return null; } else { attachedTo = attachTo; return attachedAs; } } private boolean detachFrom(SquidDatabase detachFrom) { if (detachFrom.tryExecSql("DETACH '" + getAttachedName() + "'")) { attachedTo = null; releaseExclusiveLock(); return true; } return false; } private String getAttachedName() { return getName().replace('.', '_'); } /** * Subclasses can override this method to enable connecting to a different version of SQLite than the default * version shipped with Android. For example, the squidb-sqlite-bindings project provides a class * SQLiteBindingsDatabaseOpenHelper to facilitate binding to a custom native build of SQLite. Overriders of this * method could simply <code>return new SQLiteBindingsDatabaseOpenHelper(context, databaseName, delegate, version);</code> * if they wanted to bypass Android's version of SQLite and use the version included with that project. * <p> * If you don't override this method, the stock Android SQLite build will be used. This is generally fine unless you * have a specific reason to prefer some other version of SQLite. */ protected SQLiteOpenHelperWrapper getOpenHelper(Context context, String databaseName, OpenHelperDelegate delegate, int version) { return new DefaultOpenHelperWrapper(context, databaseName, delegate, version); } /** * @return true if a connection to the {@link SQLiteDatabase} is open, false otherwise */ public synchronized final boolean isOpen() { return database != null && database.isOpen(); } /** * Close the database if it has been opened previously. This method acquires the exclusive lock before closing the * db -- it will block if other threads are in transactions. This method will throw an exception if called from * within a transaction. * <p> * It is not safe to call this method from within any of the database open or migration hooks (e.g. * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int)}, {@link #onOpen(SQLiteDatabaseWrapper)}, * {@link #onMigrationFailed(MigrationFailedException)}), etc. * <p> * WARNING: Any open database resources (e.g. cursors) will be invalid after calling this method. Do not call this * method if any open cursors may be in use. */ public final void close() { acquireExclusiveLock(); try { closeLocked(); } finally { releaseExclusiveLock(); } } private synchronized void closeLocked() { if (isOpen()) { database.close(); } helper = null; setDatabase(null); } /** * Clear all data in the database. This method acquires the exclusive lock before closing the db -- it will block * if other threads are in transactions. This method will throw an exception if called from within a transaction. * <p> * It is not safe to call this method from within any of the database open or migration hooks (e.g. * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int)}, {@link #onOpen(SQLiteDatabaseWrapper)}, * {@link #onMigrationFailed(MigrationFailedException)}), etc. * <p> * WARNING: Any open database resources (e.g. cursors) will be invalid after calling this method. Do not call this * method if any open cursors may be in use. The existing database file will be deleted and all data will be lost. */ public final void clear() { acquireExclusiveLock(); try { close(); context.deleteDatabase(getName()); } finally { releaseExclusiveLock(); } } /** * Clears the database and recreates an empty version of it. This method acquires the exclusive lock before closing * the db -- it will block if other threads are in transactions. This method will throw an exception if called from * within a transaction. * <p> * If called from within the {@link #onUpgrade(SQLiteDatabaseWrapper, int, int)} or * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int)} hooks, this method will abort the remainder of the * migration and simply clear the database. This method is also safe to call from within * {@link #onMigrationFailed(MigrationFailedException)} * <p> * WARNING: Any open database resources (e.g. cursors) will be invalid after calling this method. Do not call this * method if any open cursors may be in use. The existing database file will be deleted and all data will be lost, * with a new empty database taking its place. * * @see #clear() */ public final void recreate() { if (isInMigration) { throw new RecreateDuringMigrationException(); } else if (isInMigrationFailedHook) { recreateLocked(); // Safe to call here, necessary locks are already held in this case } else { acquireExclusiveLock(); try { recreateLocked(); } finally { releaseExclusiveLock(); } } } private synchronized void recreateLocked() { closeLocked(); context.deleteDatabase(getName()); getDatabase(); } /** * @return a human-readable database name for debugging */ @Override public String toString() { return "DB:" + getName(); } /** * Execute a raw sqlite query. This method takes an Object[] for the arguments because Android's default behavior * of binding all arguments as strings can have unexpected bugs, particularly when working with functions. For * example: * * <pre> * select * from t where _id = '1'; // Returns the first row * select * from t where abs(_id) = '1'; // Always returns empty set * </pre> * * To eliminate this class of bugs, we bind all arguments as their native types, not as strings. Any object in the * array that is not a basic type (Number, String, Boolean, etc.) will be converted to a sanitized string before * binding. * * @param sql a sql statement * @param sqlArgs arguments to bind to the sql statement * @return a {@link Cursor} containing results of the query */ public Cursor rawQuery(String sql, Object[] sqlArgs) { acquireNonExclusiveLock(); try { return getDatabase().rawQuery(sql, sqlArgs); } finally { releaseNonExclusiveLock(); } } // For use only when validating queries private void compileStatement(String sql) { acquireNonExclusiveLock(); try { getDatabase().ensureSqlCompiles(sql); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insert(String table, String nullColumnHack, ContentValues values) */ protected long insert(String table, String nullColumnHack, ContentValues values) { acquireNonExclusiveLock(); try { return getDatabase().insert(table, nullColumnHack, values); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insertOrThrow(String table, String nullColumnHack, ContentValues values) */ protected long insertOrThrow(String table, String nullColumnHack, ContentValues values) { acquireNonExclusiveLock(); try { return getDatabase().insertOrThrow(table, nullColumnHack, values); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insertWithOnConflict(String, String, android.content.ContentValues, int) */ protected long insertWithOnConflict(String table, String nullColumnHack, ContentValues values, int conflictAlgorithm) { acquireNonExclusiveLock(); try { return getDatabase().insertWithOnConflict(table, nullColumnHack, values, conflictAlgorithm); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Insert} statement * * @return the row id of the last row inserted on success, -1 on failure */ private long insertInternal(Insert insert) { CompiledStatement compiled = insert.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeInsert(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#delete(String, String, String[]) */ protected int delete(String table, String whereClause, String[] whereArgs) { acquireNonExclusiveLock(); try { return getDatabase().delete(table, whereClause, whereArgs); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Delete} statement * * @return the number of rows deleted on success, -1 on failure */ private int deleteInternal(Delete delete) { CompiledStatement compiled = delete.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeUpdateDelete(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#update(String table, ContentValues values, String whereClause, String[] whereArgs) */ protected int update(String table, ContentValues values, String whereClause, String[] whereArgs) { acquireNonExclusiveLock(); try { return getDatabase().update(table, values, whereClause, whereArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#updateWithOnConflict(String table, ContentValues values, String whereClause, String[] * whereArgs, int conflictAlgorithm) */ protected int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm) { acquireNonExclusiveLock(); try { return getDatabase().updateWithOnConflict(table, values, whereClause, whereArgs, conflictAlgorithm); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Update} statement * * @return the number of rows updated on success, -1 on failure */ private int updateInternal(Update update) { CompiledStatement compiled = update.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeUpdateDelete(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * Begin a transaction. This acquires a non-exclusive lock. * * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransaction() */ public void beginTransaction() { acquireNonExclusiveLock(); try { getDatabase().beginTransaction(); transactionSuccessState.get().beginTransaction(); } catch (RuntimeException e) { // Only release lock if begin xact was not successful releaseNonExclusiveLock(); throw e; } } /** * Begin a non-exclusive transaction. This acquires a non-exclusive lock. * * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionNonExclusive() */ public void beginTransactionNonExclusive() { acquireNonExclusiveLock(); try { getDatabase().beginTransactionNonExclusive(); transactionSuccessState.get().beginTransaction(); } catch (RuntimeException e) { // Only release lock if begin xact was not successful releaseNonExclusiveLock(); throw e; } } /** * Begin a transaction with a listener. This acquires a non-exclusive lock. * * @param listener the transaction listener * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionWithListener(android.database.sqlite.SQLiteTransactionListener) */ public void beginTransactionWithListener(SquidTransactionListener listener) { acquireNonExclusiveLock(); try { getDatabase().beginTransactionWithListener(listener); transactionSuccessState.get().beginTransaction(); } catch (RuntimeException e) { // Only release lock if begin xact was not successful releaseNonExclusiveLock(); throw e; } } /** * Begin a non-exclusive transaction with a listener. This acquires a non-exclusive lock. * * @param listener the transaction listener * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionWithListenerNonExclusive(android.database.sqlite.SQLiteTransactionListener) */ public void beginTransactionWithListenerNonExclusive(SquidTransactionListener listener) { acquireNonExclusiveLock(); try { getDatabase().beginTransactionWithListenerNonExclusive(listener); transactionSuccessState.get().beginTransaction(); } catch (RuntimeException e) { // Only release lock if begin xact was not successful releaseNonExclusiveLock(); throw e; } } /** * Mark the current transaction as successful * * @see SQLiteDatabase#setTransactionSuccessful() */ public void setTransactionSuccessful() { getDatabase().setTransactionSuccessful(); transactionSuccessState.get().setTransactionSuccessful(); } /** * @return true if a transaction is active * @see SQLiteDatabase#inTransaction() */ public synchronized boolean inTransaction() { return database != null && database.inTransaction(); } /** * End the current transaction * * @see SQLiteDatabase#endTransaction() */ public void endTransaction() { TransactionSuccessState successState = transactionSuccessState.get(); try { getDatabase().endTransaction(); } catch (RuntimeException e) { successState.unsetTransactionSuccessful(); throw e; } finally { releaseNonExclusiveLock(); successState.endTransaction(); if (!successState.inTransaction()) { flushAccumulatedNotifications(successState.outerTransactionSuccess); successState.reset(); } } } // Tracks nested transaction success or failure state. If any // nested transaction fails, the entire outer transaction // is also considered to have failed. private static class TransactionSuccessState { Deque<Boolean> nestedSuccessStack = new LinkedList<Boolean>(); boolean outerTransactionSuccess = true; private void beginTransaction() { nestedSuccessStack.push(false); } private boolean inTransaction() { return nestedSuccessStack.size() > 0; } private void setTransactionSuccessful() { nestedSuccessStack.pop(); nestedSuccessStack.push(true); } // For when endTransaction throws private void unsetTransactionSuccessful() { nestedSuccessStack.pop(); nestedSuccessStack.push(false); } private void endTransaction() { Boolean mostRecentTransactionSuccess = nestedSuccessStack.pop(); if (!mostRecentTransactionSuccess) { outerTransactionSuccess = false; } } private void reset() { nestedSuccessStack.clear(); outerTransactionSuccess = true; } } private ThreadLocal<TransactionSuccessState> transactionSuccessState = new ThreadLocal<TransactionSuccessState>() { protected TransactionSuccessState initialValue() { return new TransactionSuccessState(); } }; /** * Yield the current transaction * * @see SQLiteDatabase#yieldIfContendedSafely() */ public boolean yieldIfContendedSafely() { return getDatabase().yieldIfContendedSafely(); } /** * Convenience method for calling {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver) * ContentResolver.notifyChange(uri, null)}. * * @param uri the Uri to notify */ public void notifyChange(Uri uri) { context.getContentResolver().notifyChange(uri, null); } /** * Convenience method for calling {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver) * ContentResolver.notifyChange(uri, null)} on all the provided Uris. * * @param uris the Uris to notify */ public void notifyChange(Collection<Uri> uris) { if (uris != null && !uris.isEmpty()) { ContentResolver resolver = context.getContentResolver(); for (Uri uri : uris) { resolver.notifyChange(uri, null); } } } /** * Acquires an exclusive lock on the database. This is semantically similar to acquiring a write lock in a {@link * java.util.concurrent.locks.ReadWriteLock ReadWriteLock} but it is not generally necessary for protecting actual * database writes--it's only necessary when exclusive use of the database connection is required (e.g. while the * database is attached to another database). * <p> * Only one thread can hold an exclusive lock at a time. Calling this while on a thread that already holds a non- * exclusive lock is an error and will deadlock! We will throw an exception if this method is called while the * calling thread is in a transaction. Otherwise, this method will block until all non-exclusive locks * acquired with {@link #acquireNonExclusiveLock()} have been released, but will prevent any new non-exclusive * locks from being acquired while it blocks. */ @Beta protected void acquireExclusiveLock() { if (readWriteLock.getReadHoldCount() > 0 && readWriteLock.getWriteHoldCount() == 0) { throw new IllegalStateException("Can't acquire an exclusive lock when the calling thread is in a " + "transaction or otherwise holds a non-exclusive lock and not the exclusive lock"); } readWriteLock.writeLock().lock(); } /** * Release the exclusive lock acquired by {@link #acquireExclusiveLock()} */ @Beta protected void releaseExclusiveLock() { readWriteLock.writeLock().unlock(); } /** * Acquire a non-exclusive lock on the database. This is semantically similar to acquiring a read lock in a {@link * java.util.concurrent.locks.ReadWriteLock ReadWriteLock} but may also be used in most cases to protect database * writes (see {@link #acquireExclusiveLock()} for why this is true). This will block if the exclusive lock is held * by some other thread. Many threads can hold non-exclusive locks as long as no thread holds the exclusive lock. */ @Beta protected void acquireNonExclusiveLock() { readWriteLock.readLock().lock(); } /** * Releases a non-exclusive lock acquired with {@link #acquireNonExclusiveLock()} */ @Beta protected void releaseNonExclusiveLock() { readWriteLock.readLock().unlock(); } /** * Delegate class passed to a {@link SQLiteOpenHelperWrapper} instance that allows the SQLiteOpenHelperWrapper to call back * into its owning SquidDatabase after the database has been created or opened. */ public final class OpenHelperDelegate { private OpenHelperDelegate() { // No public instantiation } /** * Called to create the database tables */ public void onCreate(SQLiteDatabaseWrapper db) { setDatabase(db); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); // create tables Table[] tables = getTables(); if (tables != null) { for (Table table : tables) { table.appendCreateTableSql(getSqliteVersion(), sql, sqlVisitor); db.execSQL(sql.toString()); sql.setLength(0); } } View[] views = getViews(); if (views != null) { for (View view : views) { view.createViewSql(getSqliteVersion(), sql); db.execSQL(sql.toString()); sql.setLength(0); } } Index[] indexes = getIndexes(); if (indexes != null) { for (Index idx : indexes) { tryCreateIndex(idx); } } // post-table-creation SquidDatabase.this.onTablesCreated(db); } /** * Called to upgrade the database to a new version */ public void onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { setDatabase(db); boolean success = false; Throwable thrown = null; isInMigration = true; try { success = SquidDatabase.this.onUpgrade(db, oldVersion, newVersion); } catch (Throwable t) { thrown = t; success = false; } finally { isInMigration = false; } if (thrown instanceof RecreateDuringMigrationException) { throw (RecreateDuringMigrationException) thrown; } else if (thrown instanceof MigrationFailedException) { throw (MigrationFailedException) thrown; } else if (!success) { throw new MigrationFailedException(getName(), oldVersion, newVersion, thrown); } } /** * Called to downgrade the database to an older version */ public void onDowngrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { setDatabase(db); boolean success = false; Throwable thrown = null; isInMigration = true; try { success = SquidDatabase.this.onDowngrade(db, oldVersion, newVersion); } catch (Throwable t) { thrown = t; success = false; } finally { isInMigration = false; } if (thrown instanceof RecreateDuringMigrationException) { throw (RecreateDuringMigrationException) thrown; } else if (thrown instanceof MigrationFailedException) { throw (MigrationFailedException) thrown; } else if (!success) { throw new MigrationFailedException(getName(), oldVersion, newVersion, thrown); } } public void onConfigure(SQLiteDatabaseWrapper db) { setDatabase(db); SquidDatabase.this.onConfigure(db); } public void onOpen(SQLiteDatabaseWrapper db) { setDatabase(db); SquidDatabase.this.onOpen(db); } } private synchronized void setDatabase(SQLiteDatabaseWrapper db) { // If we're already holding a reference to the same object, don't need to update or recalculate the version if (database != null && db != null && db.getWrappedDatabase() == database.getWrappedDatabase()) { return; } sqliteVersion = db != null ? readSqliteVersionLocked(db) : null; database = db; } private VersionCode readSqliteVersionLocked(SQLiteDatabaseWrapper db) { try { String versionString = db.simpleQueryForString("select sqlite_version()", null); return VersionCode.parse(versionString); } catch (RuntimeException e) { onError("Failed to read sqlite version", e); throw e; } } /** * Add a column to a table by specifying the corresponding {@link Property} * * @param property the Property associated with the column to add * @return true if the statement executed without error, false otherwise */ protected boolean tryAddColumn(Property<?> property) { if (!(property.table instanceof Table)) { throw new IllegalArgumentException("Can't alter table: property does not belong to a Table"); } SqlConstructorVisitor visitor = new SqlConstructorVisitor(); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); sql.append("ALTER TABLE ").append(property.table.getExpression()).append(" ADD "); property.accept(visitor, sql); return tryExecSql(sql.toString()); } /** * Create a new {@link Table} or {@link VirtualTable} in the database * * @param table the Table or VirtualTable to create * @return true if the statement executed without error, false otherwise */ protected boolean tryCreateTable(Table table) { SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); table.appendCreateTableSql(getSqliteVersion(), sql, sqlVisitor); return tryExecSql(sql.toString()); } /** * Drop a {@link Table} or {@link VirtualTable} in the database if it exists * * @param table the Table or VirtualTable to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropTable(Table table) { return tryExecSql("DROP TABLE IF EXISTS " + table.getExpression()); } /** * Create a new {@link View} in the database * * @param view the View to create * @return true if the statement executed without error, false otherwise * @see com.yahoo.squidb.sql.View#fromQuery(com.yahoo.squidb.sql.Query, String) * @see com.yahoo.squidb.sql.View#temporaryFromQuery(com.yahoo.squidb.sql.Query, String) */ public boolean tryCreateView(View view) { StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); view.createViewSql(getSqliteVersion(), sql); return tryExecSql(sql.toString()); } /** * Drop a {@link View} in the database if it exists * * @param view the View to drop * @return true if the statement executed without error, false otherwise */ public boolean tryDropView(View view) { return tryExecSql("DROP VIEW IF EXISTS " + view.getExpression()); } /** * Create a new {@link Index} in the database * * @param index the Index to create * @return true if the statement executed without error, false otherwise * @see com.yahoo.squidb.sql.Table#index(String, com.yahoo.squidb.sql.Property[]) * @see com.yahoo.squidb.sql.Table#uniqueIndex(String, com.yahoo.squidb.sql.Property[]) */ protected boolean tryCreateIndex(Index index) { return tryCreateIndex(index.getName(), index.getTable(), index.isUnique(), index.getProperties()); } /** * Create a new {@link Index} in the database * * @param indexName name for the Index * @param table the table to create the index on * @param unique true if the index is a unique index on the specified columns * @param properties the columns to create the index on * @return true if the statement executed without error, false otherwise */ protected boolean tryCreateIndex(String indexName, Table table, boolean unique, Property<?>... properties) { if (properties == null || properties.length == 0) { onError(String.format("Cannot create index %s: no properties specified", indexName), null); return false; } StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); sql.append("CREATE "); if (unique) { sql.append("UNIQUE "); } sql.append("INDEX IF NOT EXISTS ").append(indexName).append(" ON ").append(table.getExpression()) .append("("); for (Property<?> p : properties) { sql.append(p.getName()).append(","); } sql.deleteCharAt(sql.length() - 1); sql.append(")"); return tryExecSql(sql.toString()); } /** * Drop an {@link Index} if it exists * * @param index the Index to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropIndex(Index index) { return tryDropIndex(index.getName()); } /** * Drop an {@link Index} if it exists * * @param indexName the name of the Index to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropIndex(String indexName) { return tryExecSql("DROP INDEX IF EXISTS " + indexName); } /** * Execute a {@link SqlStatement} * * @param statement the statement to execute * @return true if the statement executed without error, false otherwise */ public boolean tryExecStatement(SqlStatement statement) { CompiledStatement compiled = statement.compile(getSqliteVersion()); return tryExecSql(compiled.sql, compiled.sqlArgs); } /** * Execute a raw SQL statement * * @param sql the statement to execute * @return true if the statement executed without an error * @see SQLiteDatabase#execSQL(String) */ public boolean tryExecSql(String sql) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql); return true; } catch (RuntimeException e) { onError("Failed to execute statement: " + sql, e); return false; } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement. May throw a runtime exception if there is an error parsing the SQL or some other * error * * @param sql the statement to execute * @see SQLiteDatabase#execSQL(String) */ public void execSqlOrThrow(String sql) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql); } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement with optional arguments. The sql string may contain '?' placeholders for the * arguments. * * @param sql the statement to execute * @param bindArgs the arguments to bind to the statement * @return true if the statement executed without an error * @see SQLiteDatabase#execSQL(String, Object[]) */ public boolean tryExecSql(String sql, Object[] bindArgs) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql, bindArgs); return true; } catch (RuntimeException e) { onError("Failed to execute statement: " + sql, e); return false; } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement with optional arguments. The sql string may contain '?' placeholders for the * arguments. May throw a runtime exception if there is an error parsing the SQL or some other error * * @param sql the statement to execute * @param bindArgs the arguments to bind to the statement * @see SQLiteDatabase#execSQL(String, Object[]) */ public void execSqlOrThrow(String sql, Object[] bindArgs) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql, bindArgs); } finally { releaseNonExclusiveLock(); } } /** * @return the current SQLite version as a {@link VersionCode} * @throws RuntimeException if the version could not be read */ public VersionCode getSqliteVersion() { VersionCode toReturn = sqliteVersion; if (toReturn == null) { acquireNonExclusiveLock(); try { synchronized (this) { getDatabase(); // Opening the database will populate the sqliteVersion field return sqliteVersion; } } finally { releaseNonExclusiveLock(); } } return toReturn; } /** * Visitor that builds column definitions for {@link Property}s */ private static class SqlConstructorVisitor implements PropertyVisitor<Void, StringBuilder> { private Void appendColumnDefinition(String type, Property<?> property, StringBuilder sql) { sql.append(property.getName()).append(" ").append(type); if (!TextUtils.isEmpty(property.getColumnDefinition())) { sql.append(" ").append(property.getColumnDefinition()); } return null; } @Override public Void visitDouble(Property<Double> property, StringBuilder sql) { return appendColumnDefinition("REAL", property, sql); } @Override public Void visitInteger(Property<Integer> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitLong(Property<Long> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitString(Property<String> property, StringBuilder sql) { return appendColumnDefinition("TEXT", property, sql); } @Override public Void visitBoolean(Property<Boolean> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitBlob(Property<byte[]> property, StringBuilder sql) { return appendColumnDefinition("BLOB", property, sql); } } private static class RecreateDuringMigrationException extends RuntimeException { /* suppress compiler warning */ private static final long serialVersionUID = 480910684116077495L; } /** * Exception thrown when an upgrade or downgrade fails for any reason. Clients that want to provide more * information about why an upgrade or downgrade failed can subclass this class and throw it intentionally in * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade()} or * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade()}, and it will be forwarded to * {@link #onMigrationFailed(MigrationFailedException) onMigrationFailed()}. */ public static class MigrationFailedException extends RuntimeException { /* suppress compiler warning */ private static final long serialVersionUID = 2949995666882182744L; public final String dbName; public final int oldVersion; public final int newVersion; public MigrationFailedException(String dbName, int oldVersion, int newVersion) { this(dbName, oldVersion, newVersion, null); } public MigrationFailedException(String dbName, int oldVersion, int newVersion, Throwable throwable) { super(throwable); this.dbName = dbName; this.oldVersion = oldVersion; this.newVersion = newVersion; } @Override @SuppressLint("DefaultLocale") public String getMessage() { return String.format("Failed to migrate db \"%s\" from version %d to %d", dbName, oldVersion, newVersion); } } /** * Query the database * * @param modelClass the type to parameterize the cursor by. If the query does not contain a FROM clause, the table * or view corresponding to this model class will be used. * @param query the query to execute * @return a {@link SquidCursor} containing the query results */ public <TYPE extends AbstractModel> SquidCursor<TYPE> query(Class<TYPE> modelClass, Query query) { if (!query.hasTable() && modelClass != null) { SqlTable<?> table = getSqlTable(modelClass); if (table == null) { throw new IllegalArgumentException("Query has no FROM clause and model class " + modelClass.getSimpleName() + " has no associated table"); } query = query.from(table); // If argument was frozen, we may get a new object } CompiledStatement compiled = query.compile(getSqliteVersion()); if (compiled.needsValidation) { String validateSql = query.sqlForValidation(getSqliteVersion()); compileStatement(validateSql); // throws if the statement fails to compile } Cursor cursor = rawQuery(compiled.sql, compiled.sqlArgs); return new SquidCursor<TYPE>(cursor, query.getFields()); } /** * Fetch the specified model object with the given row ID * * @param modelClass the model class to fetch * @param id the row ID of the item * @param properties the {@link Property properties} to read * @return an instance of the model with the given ID, or null if no record was found */ public <TYPE extends TableModel> TYPE fetch(Class<TYPE> modelClass, long id, Property<?>... properties) { SquidCursor<TYPE> cursor = fetchItemById(modelClass, id, properties); return returnFetchResult(modelClass, cursor); } /** * Fetch the first model matching the given {@link Criterion}. This is useful if you expect uniqueness of models * with respect to the given criterion. * * @param modelClass the model class to fetch * @param properties the {@link Property properties} to read * @param criterion the criterion to match * @return an instance of the model matching the given criterion, or null if no record was found */ public <TYPE extends AbstractModel> TYPE fetchByCriterion(Class<TYPE> modelClass, Criterion criterion, Property<?>... properties) { SquidCursor<TYPE> cursor = fetchFirstItem(modelClass, criterion, properties); return returnFetchResult(modelClass, cursor); } /** * Fetch the first model matching the query. This is useful if you expect uniqueness of models with respect to the * given query. * * @param modelClass the model class to fetch * @param query the query to execute * @return an instance of the model returned by the given query, or null if no record was found */ public <TYPE extends AbstractModel> TYPE fetchByQuery(Class<TYPE> modelClass, Query query) { SquidCursor<TYPE> cursor = fetchFirstItem(modelClass, query); return returnFetchResult(modelClass, cursor); } protected <TYPE extends AbstractModel> TYPE returnFetchResult(Class<TYPE> modelClass, SquidCursor<TYPE> cursor) { try { if (cursor.getCount() == 0) { return null; } TYPE toReturn = modelClass.newInstance(); toReturn.readPropertiesFromCursor(cursor); return toReturn; } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } finally { cursor.close(); } } /** * Delete the row with the given row ID * * @param modelClass the model class corresponding to the table to delete from * @param id the row ID of the record * @return true if delete was successful */ public boolean delete(Class<? extends TableModel> modelClass, long id) { Table table = getTable(modelClass); int rowsUpdated = deleteInternal(Delete.from(table).where(table.getIdProperty().eq(id))); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, id); } return rowsUpdated > 0; } /** * Delete all rows matching the given {@link Criterion} * * @param modelClass model class for the table to delete from * @param where the Criterion to match. Note: passing null will delete all rows! * @return the number of deleted rows */ public int deleteWhere(Class<? extends TableModel> modelClass, Criterion where) { Table table = getTable(modelClass); Delete delete = Delete.from(table); if (where != null) { delete.where(where); } int rowsUpdated = deleteInternal(delete); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, TableModel.NO_ID); } return rowsUpdated; } /** * Delete all rows for table corresponding to the given model class * * @param modelClass model class for the table to delete from * @return the number of deleted rows */ public int deleteAll(Class<? extends TableModel> modelClass) { return deleteWhere(modelClass, null); } /** * Executes a {@link Delete} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #delete(Class, long) delete} or * {@link #deleteWhere(Class, Criterion) deleteWhere} for deleting database rows. This is provided as a convenience * in case there exists a non-ORM case where a more traditional SQL delete statement is required. * * @param delete the statement to execute * @return the number of rows deleted on success, -1 on failure */ public int delete(Delete delete) { int result = deleteInternal(delete); if (result > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, delete.getTable(), TableModel.NO_ID); } return result; } /** * Update all rows matching the given {@link Criterion}, setting values based on the provided template model. For * example, this code would change all persons' names from "joe" to "bob": * * <pre> * Person template = new Person(); * template.setName(&quot;bob&quot;); * update(Person.NAME.eq(&quot;joe&quot;), template); * </pre> * * @param where the criterion to match. Note: passing null will update all rows! * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @return the number of updated rows */ public int update(Criterion where, TableModel template) { return updateWithOnConflict(where, template, null); } /** * Update all rows in the table corresponding to the class of the given template * * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @return the number of updated rows */ public int updateAll(TableModel template) { return update(null, template); } /** * Update all rows matching the given {@link Criterion}, setting values based on the provided template model. Any * constraint violations will be resolved using the specified {@link TableStatement.ConflictAlgorithm}. * * @param where the criterion to match. Note: passing null will update all rows! * @param template a model containing new values for the properties (columns) that should be updated * @param conflictAlgorithm the conflict algorithm to use * @return the number of updated rows * @see #update(Criterion, TableModel) */ public int updateWithOnConflict(Criterion where, TableModel template, TableStatement.ConflictAlgorithm conflictAlgorithm) { Class<? extends TableModel> modelClass = template.getClass(); Table table = getTable(modelClass); Update update = Update.table(table).fromTemplate(template); if (where != null) { update.where(where); } if (conflictAlgorithm != null) { update.onConflict(conflictAlgorithm); } int rowsUpdated = updateInternal(update); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, template, table, TableModel.NO_ID); } return rowsUpdated; } /** * Update all rows in the table corresponding to the class of the given template * * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @param conflictAlgorithm the conflict algorithm to use * @return the number of updated rows */ public int updateAllWithOnConflict(TableModel template, TableStatement.ConflictAlgorithm conflictAlgorithm) { return updateWithOnConflict(null, template, conflictAlgorithm); } /** * Executes an {@link Update} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #update(Criterion, TableModel)} * or {@link #updateWithOnConflict(Criterion, TableModel, com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm)} * for bulk database updates. This is provided as a convenience in case there exists a non-ORM case where a more * traditional SQL update statement is required for some reason. * * @param update statement to execute * @return the number of rows updated on success, -1 on failure */ public int update(Update update) { int result = updateInternal(update); if (result > 0) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, null, update.getTable(), TableModel.NO_ID); } return result; } /** * Save a model to the database. Creates a new row if the model does not have an ID, otherwise updates the row with * the corresponding row ID. If a new row is inserted, the model will have its ID set to the corresponding row ID. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean persist(TableModel item) { return persistWithOnConflict(item, null); } /** * Save a model to the database. Creates a new row if the model does not have an ID, otherwise updates the row with * the corresponding row ID. If a new row is inserted, the model will have its ID set to the corresponding row ID. * Any constraint violations will be resolved using the specified {@link TableStatement.ConflictAlgorithm}. * * @param item the model to save * @param conflictAlgorithm the conflict algorithm to use * @return true if current the model data is stored in the database * @see #persist(TableModel) */ public boolean persistWithOnConflict(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { if (!item.isSaved()) { return insertRow(item, conflictAlgorithm); } if (!item.isModified()) { return true; } return updateRow(item, conflictAlgorithm); } /** * Save a model to the database. This method always inserts a new row and sets the ID of the model to the * corresponding row ID. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean createNew(TableModel item) { item.setId(TableModel.NO_ID); return insertRow(item, null); } /** * Save a model to the database. This method always updates an existing row with a row ID corresponding to the * model's ID. If the model doesn't have an ID, or the corresponding row no longer exists in the database, this * will return false. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean saveExisting(TableModel item) { return updateRow(item, null); } /** * Inserts a new row using the item's merged values into the DB. * <p> * Note: unlike {@link #createNew(TableModel)}, which will always create a new row even if an id is set on the * model, this method will blindly attempt to insert the primary key id value if it is provided. This may cause * conflicts, throw exceptions, etc. if the row id already exists, so be sure to check for such cases if you * expect they may happen. * * @param item the model to insert * @return true if success, false otherwise */ protected final boolean insertRow(TableModel item) { return insertRow(item, null); } /** * Same as {@link #insertRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint * violations * * @param item the model to insert * @param conflictAlgorithm the conflict algorithm to use * @return true if success, false otherwise */ protected final boolean insertRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { Class<? extends TableModel> modelClass = item.getClass(); Table table = getTable(modelClass); long newRow; ContentValues mergedValues = item.getMergedValues(); if (mergedValues.size() == 0) { return false; } if (conflictAlgorithm == null) { newRow = insertOrThrow(table.getExpression(), null, mergedValues); } else { newRow = insertWithOnConflict(table.getExpression(), null, mergedValues, conflictAlgorithm.getAndroidValue()); } boolean result = newRow > 0; if (result) { notifyForTable(DataChangedNotifier.DBOperation.INSERT, item, table, newRow); item.setId(newRow); item.markSaved(); } return result; } /** * Update an existing row in the database using the item's setValues. The item must have the primary key id set; * if it does not, the method will return false. * * @param item the model to save * @return true if success, false otherwise */ protected final boolean updateRow(TableModel item) { return updateRow(item, null); } /** * Same as {@link #updateRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint * violations * * @param item the model to save * @param conflictAlgorithm the conflict algorithm to use * @return true if success, false otherwise */ protected final boolean updateRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { if (!item.isModified()) { // nothing changed return true; } if (!item.isSaved()) { return false; } Class<? extends TableModel> modelClass = item.getClass(); Table table = getTable(modelClass); Update update = Update.table(table).fromTemplate(item).where(table.getIdProperty().eq(item.getId())); if (conflictAlgorithm != null) { update.onConflict(conflictAlgorithm); } boolean result = updateInternal(update) > 0; if (result) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, item, table, item.getId()); item.markSaved(); } return result; } /** * Executes an {@link Insert} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #persist(TableModel) persist} or * {@link #createNew(TableModel) createNew} for inserting database rows. This is provided as a convenience in case * there exists a non-ORM case where a more traditional SQL insert statement is required. * * @param insert the statement to execute * @return the row id of the last row inserted on success, 0 on failure */ public long insert(Insert insert) { long result = insertInternal(insert); if (result > TableModel.NO_ID) { int numInserted = insert.getNumRows(); notifyForTable(DataChangedNotifier.DBOperation.INSERT, null, insert.getTable(), numInserted == 1 ? result : TableModel.NO_ID); } return result; } protected <TYPE extends TableModel> SquidCursor<TYPE> fetchItemById(Class<TYPE> modelClass, long id, Property<?>... properties) { Table table = getTable(modelClass); return fetchFirstItem(modelClass, table.getIdProperty().eq(id), properties); } protected <TYPE extends AbstractModel> SquidCursor<TYPE> fetchFirstItem(Class<TYPE> modelClass, Criterion criterion, Property<?>... properties) { return fetchFirstItem(modelClass, Query.select(properties).where(criterion)); } protected <TYPE extends AbstractModel> SquidCursor<TYPE> fetchFirstItem(Class<TYPE> modelClass, Query query) { boolean immutableQuery = query.isImmutable(); Field<Integer> beforeLimit = query.getLimit(); SqlTable<?> beforeTable = query.getTable(); query = query.limit(1); // If argument was frozen, we may get a new object SquidCursor<TYPE> cursor = query(modelClass, query); if (!immutableQuery) { query.from(beforeTable).limit(beforeLimit); // Reset for user } cursor.moveToFirst(); return cursor; } /** * Count the number of rows matching a given {@link Criterion}. Use null to count all rows. * * @param modelClass the model class corresponding to the table * @param criterion the criterion to match * @return the number of rows matching the given criterion */ public int count(Class<? extends AbstractModel> modelClass, Criterion criterion) { Property.IntegerProperty countProperty = Property.IntegerProperty.countProperty(); Query query = Query.select(countProperty); if (criterion != null) { query.where(criterion); } SquidCursor<?> cursor = query(modelClass, query); try { cursor.moveToFirst(); return cursor.get(countProperty); } finally { cursor.close(); } } /** * Count the number of rows in the given table. * * @param modelClass the model class corresponding to the table * @return the number of rows in the table */ public int countAll(Class<? extends AbstractModel> modelClass) { return count(modelClass, null); } private final Object notifiersLock = new Object(); private boolean dataChangedNotificationsEnabled = true; private List<DataChangedNotifier<?>> globalNotifiers = new ArrayList<DataChangedNotifier<?>>(); private Map<SqlTable<?>, List<DataChangedNotifier<?>>> tableNotifiers = new HashMap<SqlTable<?>, List<DataChangedNotifier<?>>>(); // Using a ThreadLocal makes it easy to have one accumulator set per transaction, since // transactions are also associated with the thread they run on private ThreadLocal<Set<DataChangedNotifier<?>>> notifierAccumulator = new ThreadLocal<Set<DataChangedNotifier<?>>>() { protected Set<DataChangedNotifier<?>> initialValue() { return new HashSet<DataChangedNotifier<?>>(); } }; /** * Register a {@link DataChangedNotifier} to listen for database changes. The DataChangedNotifier object will be * notified whenever a table it is interested is modified, and can accumulate a set of notifications to send when * the current transaction or statement completes successfully. * * @param notifier the DataChangedNotifier to register */ public void registerDataChangedNotifier(DataChangedNotifier<?> notifier) { if (notifier == null) { return; } synchronized (notifiersLock) { Collection<SqlTable<?>> tables = notifier.whichTables(); if (tables == null || tables.isEmpty()) { globalNotifiers.add(notifier); } else { for (SqlTable<?> table : tables) { List<DataChangedNotifier<?>> notifiersForTable = tableNotifiers.get(table); if (notifiersForTable == null) { notifiersForTable = new ArrayList<DataChangedNotifier<?>>(); tableNotifiers.put(table, notifiersForTable); } notifiersForTable.add(notifier); } } } } /** * Unregister a {@link DataChangedNotifier} previously registered by * {@link #registerDataChangedNotifier(DataChangedNotifier)} * * @param notifier the DataChangedNotifier to unregister */ public void unregisterDataChangedNotifier(DataChangedNotifier<?> notifier) { if (notifier == null) { return; } synchronized (notifiersLock) { Collection<SqlTable<?>> tables = notifier.whichTables(); if (tables == null || tables.isEmpty()) { globalNotifiers.remove(notifier); } else { for (SqlTable<?> table : tables) { List<DataChangedNotifier<?>> notifiersForTable = tableNotifiers.get(table); if (notifiersForTable != null) { notifiersForTable.remove(notifier); } } } } } /** * Unregister all {@link DataChangedNotifier}s previously registered by * {@link #registerDataChangedNotifier(DataChangedNotifier)} */ public void unregisterAllDataChangedNotifiers() { synchronized (notifiersLock) { globalNotifiers.clear(); tableNotifiers.clear(); } } /** * Set a flag to enable or disable data change notifications. No {@link DataChangedNotifier}s will be notified * (or accumulated during transactions) while the flag is set to false. */ public void setDataChangedNotificationsEnabled(boolean enabled) { dataChangedNotificationsEnabled = enabled; } private void notifyForTable(DataChangedNotifier.DBOperation op, AbstractModel modelValues, SqlTable<?> table, long rowId) { if (!dataChangedNotificationsEnabled) { return; } synchronized (notifiersLock) { onDataChanged(globalNotifiers, op, modelValues, table, rowId); onDataChanged(tableNotifiers.get(table), op, modelValues, table, rowId); } if (!inTransaction()) { flushAccumulatedNotifications(true); } } private void onDataChanged(List<DataChangedNotifier<?>> notifiers, DataChangedNotifier.DBOperation op, AbstractModel modelValues, SqlTable<?> table, long rowId) { if (notifiers != null) { for (DataChangedNotifier<?> notifier : notifiers) { if (notifier.onDataChanged(table, this, op, modelValues, rowId)) { notifierAccumulator.get().add(notifier); } } } } private void flushAccumulatedNotifications(boolean transactionSuccess) { Set<DataChangedNotifier<?>> accumulatedNotifiers = notifierAccumulator.get(); if (!accumulatedNotifiers.isEmpty()) { for (DataChangedNotifier<?> notifier : accumulatedNotifiers) { notifier.flushAccumulatedNotifications(this, transactionSuccess && dataChangedNotificationsEnabled); } accumulatedNotifiers.clear(); } } }
package net.sf.mpxj.utility; import java.util.Calendar; import java.util.Date; /** * Utility methods for manipulating dates. */ public final class DateUtility { /** * Constructor. */ private DateUtility () { // private constructor to prevent instantiation } /** * Returns a new Date instance whose value * represents the start of the day (i.e. the time of day is 00:00:00.000) * * @param date date to convert * @return day start date */ public static Date getDayStartDate (Date date) { if (date != null) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); date = cal.getTime(); } return (date); } /** * Returns a new Date instance whose value * represents the end of the day (i.e. the time of days is 11:59:59.999) * * @param date date to convert * @return day start date */ public static Date getDayEndDate (Date date) { if (date != null) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.MILLISECOND, 999); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.HOUR_OF_DAY, 23); date = cal.getTime(); } return (date); } /** * This method resets the date part of a date time value to * a standard date (1/1/1). This is used to allow times to * be compared and manipulated. * * @param date date time value * @return date time with date set to a standard value */ public static Date getCanonicalTime (Date date) { if (date != null) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.DAY_OF_YEAR, 1); cal.set(Calendar.YEAR, 1); date = cal.getTime(); } return (date); } /** * This method compares a target date with a date range. The method will * return 0 if the date is within the range, less than zero if the date * is before the range starts, and greater than zero if the date is after * the range ends. * * @param startDate range start date * @param endDate range end date * @param targetDate target date * @return comparison result */ public static int compare (Date startDate, Date endDate, Date targetDate) { return (compare(startDate, endDate, targetDate.getTime())); } /** * This method compares a target date with a date range. The method will * return 0 if the date is within the range, less than zero if the date * is before the range starts, and greater than zero if the date is after * the range ends. * * @param startDate range start date * @param endDate range end date * @param targetDate target date in milliseconds * @return comparison result */ public static int compare (Date startDate, Date endDate, long targetDate) { int result = 0; if (targetDate < startDate.getTime()) { result = -1; } else { if (targetDate > endDate.getTime()) { result = 1; } } return (result); } }
package com.jbooktrader.indicator.balance; import com.jbooktrader.platform.indicator.*; import com.jbooktrader.platform.marketdepth.*; public class BalanceRSI extends Indicator { private final double multiplier; private double emaUp, emaDown; private double previousBalance; public BalanceRSI(MarketBook marketBook, int periodLength) { super(marketBook); multiplier = 2. / (periodLength + 1.); } @Override public double calculate() { double balance = marketBook.getLastMarketDepth().getBalance(); if (previousBalance != 0) { double change = balance - previousBalance; double up = (change > 0) ? change : 0; double down = (change < 0) ? -change : 0; emaUp += (up - emaUp) * multiplier; emaDown += (down - emaDown) * multiplier; double sum = emaUp + emaDown; value = (sum == 0) ? 50 : (100 * emaUp / sum); } else { value = 50; } previousBalance = balance; return value; } }
package org.arp.javautil.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Convenience class for executing SQL queries. * * @author Andrew Post */ public final class SQLExecutor { public static interface StatementPreparer { void prepare(PreparedStatement stmt) throws SQLException; } public static interface ResultProcessor { void process(ResultSet resultSet) throws SQLException; } public static void executeSQL(Connection connection, PreparedStatement preparedStmt, StatementPreparer stmtPreparer, ResultProcessor resultProcessor) throws SQLException { if (connection == null) throw new IllegalArgumentException("connection cannot be null"); if (stmtPreparer != null) { stmtPreparer.prepare(preparedStmt); } ResultSet resultSet = null; try { preparedStmt.execute(); if (resultProcessor != null) { resultProcessor.process(preparedStmt.getResultSet()); } } finally { if (resultSet != null) { resultSet.close(); } } } public static void executeSQL(Connection connection, String sql, ResultProcessor resultProcessor) throws SQLException { if (connection == null) throw new IllegalArgumentException("connection cannot be null"); Statement stmt = connection.createStatement(); try { ResultSet resultSet = null; try { stmt.execute(sql); if (resultProcessor != null) { resultProcessor.process(stmt.getResultSet()); } } finally { if (resultSet != null) { resultSet.close(); } } } finally { stmt.close(); } } public static void executeSQL(Connection connection, String sql, StatementPreparer stmtPreparer, ResultProcessor resultProcessor) throws SQLException { if (connection == null) throw new IllegalArgumentException("connection cannot be null"); PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); executeSQL(connection, stmt, stmtPreparer, resultProcessor); } finally { if (stmt != null) { stmt.close(); } } } public static void executeSQL(ConnectionSpec connectionCreator, String sql, ResultProcessor resultProcessor) throws SQLException { if (connectionCreator == null) throw new IllegalArgumentException( "connectionCreator cannot be null"); Connection con = null; try { con = connectionCreator.getOrCreate(); executeSQL(con, sql, resultProcessor); } finally { if (con != null) { con.close(); } } } public static void executeSQL(ConnectionSpec connectionCreator, String sql, StatementPreparer stmtPreparer, ResultProcessor resultProcessor) throws SQLException { if (connectionCreator == null) throw new IllegalArgumentException( "connectionCreator cannot be null"); Connection con = null; try { con = connectionCreator.getOrCreate(); executeSQL(con, sql, stmtPreparer, resultProcessor); } finally { if (con != null) { con.close(); } } } }
package cn.jianke.jkchat; import android.content.Context; import android.text.TextUtils; import com.jk.chat.gen.JkChatConversationDao; import com.jk.chat.gen.JkChatMessageDao; import com.jk.chat.gen.JkChatSessionDao; import java.util.ArrayList; import java.util.List; import java.util.Locale; import cn.jianke.jkchat.common.RequestUrlUtils; import cn.jianke.jkchat.common.StringUtils; import cn.jianke.jkchat.data.dao.JkChatConversationDaoWrapper; import cn.jianke.jkchat.data.dao.JkChatDaoManager; import cn.jianke.jkchat.data.dao.JkChatMessageDaoWrapper; import cn.jianke.jkchat.data.shareperferences.JkChatSharePerferences; import cn.jianke.jkchat.domain.JkChatConversation; import cn.jianke.jkchat.domain.JkChatMessage; import cn.jianke.jkchat.domain.JkChatSession; import cn.jianke.jkchat.httprequest.JkChatRequest; import de.tavendo.autobahn.WebSocket; import okhttp3.Response; public class JKChatServiceImpl implements JkChatService{ public final static int SENDSTATUS_FILTERED = 0; // EditText public final static int SENDSTATUS_CLEAN_ET = 1; public final static int SENDSTATUS_CAN_SEND = 2; public final static int SENDSTATUS_FORBID = 3; public final static int NETWORK_CONNECTION_FAILED = 1; public final static int SERVER_CONNECTION_FAILED = 2; private final static String INIT = "init"; private final static String CONNECTING = "connecting"; private final static String CONNECTED = "connected"; private final static String DISCONECTED = "disconected"; private final static String[] thanks = {"", "", "", "", ""}; private String connectStatus = INIT; private static JKChatServiceImpl instance; // api private JkChatApi mJkChatApi; private JkChatConnection mJkChatConnection; private JkChatConfig mJkChatConfig; private JkChatServiceListener mJkChatServiceListener; private boolean isChatRunning = false; private int doctorNum = 0; private boolean isForbidAsk = false; private int askingFlag; private boolean isConversationFinished = false; private OnClientClosedListener mOnClientClosedListener; public static List<JkChatMessage> tmpMessages = new ArrayList<JkChatMessage>(); private String customSessionID = "Unknow_CustomSessionID"; private String staffSessionID = "Unknow_StaffSesionID"; private JkChatConversation jkCurrentConversation; // fragment private boolean isFinishedFirstRequest = false; // Dao private JkChatConversationDao mJkChatConversationDao; // Dao private JkChatMessageDao mJkChatMessageDao; // Dao private JkChatSessionDao mJkChatSessionDao; private static Context mApplicationContext; // api private JkChatApiListener mJkChatApiListener = new JkChatApiListener() { @Override public void onReponseGetDoctorNum(int doctorNum) { if (mApplicationContext == null) return; setDoctorNum(doctorNum); // 1 ,10 if (doctorNum > 0){ sendSystemText(mApplicationContext.getResources().getString( R.string.chat_few_keyword_doctor_online_tips)); }else { sendSystemText(mApplicationContext.getResources().getString( R.string.chat_few_keyword_doctor_offline_tips)); } } @Override public void onGetDoctorNumError(Exception e) { if (mJkChatServiceListener != null) mJkChatServiceListener.onNetworkUnavaiable(NETWORK_CONNECTION_FAILED); } @Override public void onCheckUserAskingNow(int askingFlag) { setAskingFlag(askingFlag); } @Override public void onCheckUserAskingNowError(Exception e) { if (mJkChatServiceListener != null) mJkChatServiceListener.onNetworkUnavaiable(NETWORK_CONNECTION_FAILED); } }; private JkChatConnectionListener mJkChatConnectionListener = new JkChatConnectionListener() { @Override public void onOpen() { isConversationFinished = false; } @Override public void onClose(int code, String reason) { if (code == WebSocket.ConnectionHandler.CLOSE_CONNECTION_LOST && mJkChatConfig != null){ // url String checkAskingNowUrl = String.format(Locale.getDefault(), RequestUrlUtils.CHECK_ASKING_NOW_URL, mJkChatConfig.getUsername()); JkChatRequest.getInstance().getAsynHttp(checkAskingNowUrl, new JkChatRequest.ResponseCallBack() { @Override public void onSuccess(Response response) { if (response != null && response.body() != null){ String content = response.body().toString(); if (!TextUtils.isEmpty(content)){ if (StringUtils.strIsNum(content)){ int askFlag = Integer.parseInt(content); if (askFlag != 0){ jkConnection(); } } } } } @Override public void onFailure(Exception e) { } }); } try { connectStatus = DISCONECTED; isConversationFinished = true; isFinishedFirstRequest = true; } catch (Exception e) { } finally { if (code != WebSocket.ConnectionHandler.CLOSE_NORMAL && code != WebSocket.ConnectionHandler.CLOSE_CONNECTION_LOST) { if (connectStatus != CONNECTING || connectStatus != CONNECTED) { if (mJkChatServiceListener != null) mJkChatServiceListener.onNetworkUnavaiable(SERVER_CONNECTION_FAILED); } } } } @Override public void onStuffNumChanged(int number) { if (mApplicationContext == null) return; setDoctorNum(number); connectStatus = CONNECTING; if (number < 1){ sendSystemText(mApplicationContext.getResources().getString( R.string.chat_few_keyword_doctor_offline_tips)); }else { // CustomSessionID JkChatMessage tmpJkChatMessage = JkChatMessageDaoWrapper .getInstance(mApplicationContext).findLastMessage(); if (tmpJkChatMessage != null) { JkChatConversation tmpJkChatConversation = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .findLastConversation(); // CustomSessionID tmpJkChatMessage.setCustomSessionID(tmpJkChatConversation.getAccesstoken()); mJkChatMessageDao.update(tmpJkChatMessage); } } } @Override public void onSessionChanged(JkChatSession session) { if (mApplicationContext == null) return; // session if (session == null) return; createConversation(); // tidtid jkCurrentConversation.setTid(session.getTid()); // cidtidconversation JkChatMessageDaoWrapper.getInstance(mApplicationContext) .modifyTidByCid(jkCurrentConversation.getCid(), session.getTid()); JkChatConversationDaoWrapper.getInstance(mApplicationContext) .updataTidByCid(jkCurrentConversation.getCid(), session.getTid(), jkCurrentConversation.getStatus(), jkCurrentConversation.getConversationCreateTime()); connectStatus = CONNECTED; sendSystemText(mApplicationContext.getResources().getString( R.string.chat_doctor_answering_pre) + session.getStaffName() + mApplicationContext.getResources().getString( R.string.chat_doctor_answering)); if (mJkChatServiceListener != null){ mJkChatServiceListener.onStuffChanged(session.getStaffName()); JkChatMessage chatMessage = new JkChatMessage(); chatMessage.setMsg(""); chatMessage.setTid(session.getTid()); chatMessage.setMsgType(""); mJkChatServiceListener.onReceivedMessage(chatMessage); } } @Override public void onReceiveMessage(JkChatMessage message) { if (mOnClientClosedListener != null){ mOnClientClosedListener.onReceiveMessage(message); } if (mJkChatServiceListener != null) mJkChatServiceListener.onReceivedMessage(message); saveMessage(message); } @Override public void onClientClosed() { if (mApplicationContext == null) return; JkChatSharePerferences.getInstance(mApplicationContext).saveConversationStatus(true); sendSystemText(mApplicationContext.getResources().getString( R.string.chat_ending)); if (mOnClientClosedListener != null) mOnClientClosedListener.OnClientClosed(); } @Override public void onStuffOffline() { if (mApplicationContext == null) return; sendSystemText(mApplicationContext.getResources().getString( R.string.chat_doctor_lost_conn)); } @Override public void onChangetoWait() { // tid // onSessionChangedtid if (mApplicationContext == null) return; if (jkCurrentConversation != null) JkChatMessageDaoWrapper.getInstance(mApplicationContext) .removeTidByCid(jkCurrentConversation.getCid()); sendSystemText(mApplicationContext.getResources().getString( R.string.chat_doctor_change_Wait)); } @Override public void onChatClosed() { // socket jkCurrentConversation = JkChatConversation.newConversation(); connectStatus = CONNECTING; } @Override public void onChatStillAlive() { if (mApplicationContext == null) return; connectStatus = CONNECTED; jkCurrentConversation = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .findLastConversation(); } @Override public void onGetServerMessageDone() { isFinishedFirstRequest = true; } @Override public void onFilterAskQuestion() { if (mApplicationContext == null) return; sendSystemText(mApplicationContext.getResources().getString( R.string.chat_filter_word_tips)); } @Override public void onForbidAskQuestion() { if (mApplicationContext == null) return; isForbidAsk = true; sendSystemText(mApplicationContext.getResources().getString( R.string.chat_limit_ip)); } }; /** * Constructor * @author leibing * @createTime 2017/2/20 * @lastModify 2017/2/20 * @param context * @param userId id * @return */ public JKChatServiceImpl(Context context, String userId){ if (context == null){ throw new NullPointerException("context is null!"); } // init application context mApplicationContext = context.getApplicationContext(); // init jk chat api mJkChatApi = new JkChatApiImpl(userId); // set jk chat api listener mJkChatApi.setJkChatApiListener(mJkChatApiListener); // init jk chat connect mJkChatConnection = new JkChatConnectionImpl(); // set jk chat connection listener mJkChatConnection.setListener(mJkChatConnectionListener); // init jk chat conversation dao mJkChatConversationDao = JkChatDaoManager.getInstance(mApplicationContext) .getDaoSession().getJkChatConversationDao(); // init jk chat message dao mJkChatMessageDao = JkChatDaoManager.getInstance(mApplicationContext) .getDaoSession().getJkChatMessageDao(); // init jk chat session dao mJkChatSessionDao = JkChatDaoManager.getInstance(mApplicationContext) .getDaoSession().getJkChatSessionDao(); } /** * sington * @author leibing * @createTime 2017/2/20 * @lastModify 2017/2/20 * @param context * @param userId id * @return */ public static JKChatServiceImpl getInstance(Context context, String userId){ if (instance == null){ synchronized (JKChatServiceImpl.class){ if (instance == null){ instance = new JKChatServiceImpl(context, userId); } } } return instance; } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param * @return */ private void jkConnection(){ if (mJkChatConnection != null && mApplicationContext != null && mJkChatConfig != null && !mJkChatConnection.isConnected()){ String fileId = JkChatSharePerferences.getInstance( mApplicationContext).getPatientId(); String name = JkChatSharePerferences.getInstance( mApplicationContext).getPatientName(); String sex = JkChatSharePerferences.getInstance( mApplicationContext).getPatientSex(); String age = JkChatSharePerferences.getInstance( mApplicationContext).getPatientAge(); if (StringUtils.isEmpty(fileId) || StringUtils.isEmpty(name) || StringUtils.isEmpty(sex) || StringUtils.isEmpty(age) || StringUtils.isEmpty(mJkChatConfig.getUsername()) || StringUtils.isEmpty(mJkChatConfig.getClientId())) return; try { mJkChatConnection.connect(mJkChatConfig.getUsername(), mJkChatConfig.getClientId(),fileId,name,sex,age); connectStatus = CONNECTING; } catch (JkChatException e) { connectStatus = DISCONECTED; if (mJkChatServiceListener != null) mJkChatServiceListener.onNetworkUnavaiable(SERVER_CONNECTION_FAILED); e.printStackTrace(); } } } @Override public void start() { if (mApplicationContext == null) return; if (!isChatRunning){ isChatRunning = true; JkChatSharePerferences.getInstance(mApplicationContext) .saveConversationStatus(false); jkConnection(); } } @Override public void stop() { if (isChatRunning){ isChatRunning = false; if (mJkChatApi != null) mJkChatApi.cancel(); if (mJkChatConnection != null && mJkChatConnection.isConnected()) mJkChatConnection.disconnect(); } } @Override public List<JkChatMessage> readMesssages(int limit, int offset) { return null; } @Override public List<JkChatMessage> readMesssages(String cid, int limit, int offset) { return null; } @Override public String getLastTid() { return null; } @Override public int sendMessage(JkChatMessage msg) { if (!msg.getMsgType().equalsIgnoreCase(JkChatMessage.TYPE_IMG)) { int result = filterMessage(msg); if (result != SENDSTATUS_CAN_SEND) { return result; } } switch (connectStatus){ case INIT: case DISCONECTED: connectAndSendMessage(msg); return SENDSTATUS_FILTERED; case CONNECTING: // onOpen addMsgAndFilterRepeatMsg(msg); // sendAndSaveMsgByLoop(); return SENDSTATUS_FILTERED; case CONNECTED: sendAndSaveMessage(msg); break; default: break; } return SENDSTATUS_CAN_SEND; } @Override public void setListener(JkChatServiceListener listener) { this.mJkChatServiceListener = listener; } @Override public void setConfig(JkChatConfig config) { this.mJkChatConfig = config; } @Override public boolean isFinishedFirstRequest() { return isFinishedFirstRequest; } @Override public boolean isConversationFinished() { return isConversationFinished; } @Override public void saveMessage2Db(JkChatMessage msg) { } @Override public void addImgRemoteUrl(boolean finish, int id, String remoteUrl) { } @Override public void addMoreImgRemoteUrl(boolean finish, int id, ArrayList remoteUrls) { } @Override public JkChatMessage getImgMsg(int id) { return null; } @Override public boolean getConnectStatus() { if (connectStatus == CONNECTED) return true; else return false; } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param * @return */ public void setDoctorNum(int doctorNum) { this.doctorNum = doctorNum; } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param askingFlag * @return */ public void setAskingFlag(int askingFlag) { this.askingFlag = askingFlag; } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param content * @return */ public void sendSystemText(String content) { if (mApplicationContext == null) return; if (!isForbidAsk && StringUtils.isNotEmpty(content) && !mApplicationContext.getResources().getString(R.string.chat_limit_ip) .equals(content)) { JkChatMessage msg = JkChatMessage.newSystemMessage(content); if (mJkChatServiceListener != null) { mJkChatServiceListener.onReceivedMessage(msg); } }else { JkChatMessage msg = JkChatMessage.newSystemMessage(mApplicationContext.getResources() .getString(R.string.chat_limit_ip)); if (mJkChatServiceListener != null) mJkChatServiceListener.onReceivedMessage(msg); } } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param message * @return */ private int filterMessage(JkChatMessage message) { int result = SENDSTATUS_CAN_SEND; // connectStatus = ConnectStatus.INIT; if (isConversationFinished && (connectStatus != INIT)) { connectStatus = INIT; String msg = message.getMsg(); if (msg.length() < 10) { for (int i = 0; i < thanks.length; i++) { if (msg.contains(thanks[i])) { if (mJkChatServiceListener != null) { mJkChatServiceListener.onReceivedMessage(message); if (mApplicationContext != null) { sendSystemText(mApplicationContext.getResources().getString( R.string.chat_thx2doctor)); } if (mJkChatConnection != null) mJkChatConnection.clientPositionClose(message.getTid()); // EditText result = SENDSTATUS_CLEAN_ET; return result; } } } } } if (connectStatus == INIT) { String msg = message.getMsg(); if ((msg.contains("") || msg.contains("") || msg.contains("") || msg.contains("") || msg.contains("hi") || msg.contains("hello")) && msg.length() < 10) { if (isForbidAsk) { return SENDSTATUS_FORBID; } if (mJkChatApi != null) mJkChatApi.requestGetDoctorNum(); result = SENDSTATUS_FILTERED; } else if (msg.length() < 10) { if (isForbidAsk) { return SENDSTATUS_FORBID; } result = SENDSTATUS_FILTERED; } } if (isForbidAsk) { result = SENDSTATUS_FORBID; } return result; } /** * * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param message * @return */ private void addMsgAndFilterRepeatMsg(JkChatMessage message) { if (message.getMsgType().equalsIgnoreCase(JkChatMessage.TYPE_IMG)) { tmpMessages.add(message); return; } if (tmpMessages.size() != 0) { for (int i = 0; i < tmpMessages.size(); i++) { if (tmpMessages.get(i).getMsg().equals(message.getMsg())) { break; } if (i == tmpMessages.size() - 1) { tmpMessages.add(message); } } } else { tmpMessages.add(message); } } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param message * @return */ private void connectAndSendMessage(JkChatMessage message) { addMsgAndFilterRepeatMsg(message); if (connectStatus != CONNECTING || connectStatus != CONNECTED) { jkConnection(); } } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param message * @return */ private boolean sendAndSaveMessage(JkChatMessage message) { boolean sendMsgSucessed = localSendMessage(message); if (sendMsgSucessed) { // saveMessage(message); } return sendMsgSucessed; } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param message * @return */ private boolean localSendMessage(JkChatMessage message) { if (mJkChatConnection == null) return false; message.setCustomSessionID(customSessionID); message.setStaffSessionID(staffSessionID); if (jkCurrentConversation != null) message.setTid(jkCurrentConversation.getTid()); return mJkChatConnection.sendMessage(message); } /** * * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param * @return */ private void createConversation() { if (mApplicationContext == null) return; boolean getIsUserLogin = JkChatSharePerferences .getInstance(mApplicationContext).getIsUserLogin(); String isLogin = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .getLastConversationIsLogin(); int status = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .getLastConversationStatus(); if (isLogin != null && status != JkChatConversation.STATUS_NULL && Boolean.parseBoolean(isLogin) == getIsUserLogin && status != JkChatConversation.STATUS_FINISHED) { jkCurrentConversation = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .findLastConversation(); } if (jkCurrentConversation == null) { jkCurrentConversation = JkChatConversation.newConversation(); } } /** * * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param message * @return */ public void saveMessage(JkChatMessage message) { if (mApplicationContext == null) return; if (message == null) return; if (jkCurrentConversation != null){ if (mJkChatConversationDao != null && jkCurrentConversation.getId() == 0) { mJkChatConversationDao.insert(jkCurrentConversation); message.setCid(jkCurrentConversation.getCid()); } // cidcid JkChatConversation lastJkChatConversation = JkChatConversationDaoWrapper .getInstance(mApplicationContext) .findLastConversation(); if (message.getDirect().equals(JkChatMessage.DIRECT_RECEIVE) && message.getCustomSessionID() != null && lastJkChatConversation != null && lastJkChatConversation.getCid() != null){ message.setCid(lastJkChatConversation.getCid()); } } } /** * * @author leibing * @createTime 2017/2/21 * @lastModify 2017/2/21 * @param * @return */ public void setOnClientClosedListener(OnClientClosedListener mOnClientClosedListener) { this.mOnClientClosedListener = mOnClientClosedListener; } public interface OnClientClosedListener { /** * * @param */ void OnClientClosed(); /** * * @param message */ void onReceiveMessage(JkChatMessage message); } }
// Algorithm.java // Authors: // Antonio J. Nebro <antonio@lcc.uma.es> // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package org.uma.jmetal.core; /** Interface representing an algorithm */ public interface Algorithm<Result> { /** Executes the algorithm */ public void execute() ; public Result getResult() ; }
package it.speedhouse.main.statics; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class ServiziDB { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://db4free.net:3306"; static final String USER = "marcomassiema"; static final String PASS = "marcomassiema"; public static void creaDB(String nome) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql, sql2; sql = "use marcomassiema;"; sql2 = "create table database" + nome + "();"; stmt.execute(sql); stmt.execute(sql2); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); } public static ArrayList<String> ottieniTabelle(String nomeDb) { ArrayList<String> tabelle = new ArrayList<String>(); Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql, sql2; sql = "use marcomassiema;"; sql2 = "show tables;"; stmt.execute(sql); ResultSet rs = stmt.executeQuery(sql2); while (rs.next()) { String tabella = rs.getString(1); String[] db = tabella.split("_"); System.out.println(db[0]); if (db[0].equals(nomeDb)) { tabelle.add(db[1]); } } //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); return tabelle; } public static void creaTabella(String nomeDb, String[] tipi, String nomeTabella, String[] colonne) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql, sql2; sql = "use marcomassiema;"; sql2 = "CREATE TABLE " + nomeDb + "_" + nomeTabella + " ("; for (int i = 0; i < tipi.length; i++) { sql2 += colonne[i] + " "; if (ServiziGenerici.isInteger(tipi[i])) sql2 += "INT"; else if (ServiziGenerici.isDecimal(tipi[i])) sql2 += "FLOAT(8,4)"; else sql += "VARCHAR(30)"; if (tipi.length - i > 1) sql2 += ", "; } sql2 += ");"; System.out.println(sql2); stmt.execute(sql); stmt.execute(sql2); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); } /** * Non effettua controlli sulla compatibilit tra tipo dei dati inseriti e tipi accettati dalle colonne della tabella. * @param nomeDb - Nome del database in cui inserire i dati * @param nomeTabella - Nome della tabella in cui inserire i dati * @param righe - Dati da inserire */ public static void inserisciDati(String nomeDb, String nomeTabella, ArrayList<String[]> righe) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql, sql2; sql = "use marcomassiema;"; sql2 = "INSERT INTO " + nomeDb + "_" + nomeTabella + " VALUES "; for (int i = 0; i < righe.size(); i++) { String[] tupla = righe.get(i); sql2 += "("; for (int j = 0; j < tupla.length; j++) { if (ServiziGenerici.isInteger(tupla[j])) sql2 += tupla[j]; else if (ServiziGenerici.isDecimal(tupla[j])) sql2 += tupla[j]; else sql2 += "\"" + tupla[j] + "\""; if (tupla.length - j > 1) sql2 += ", "; } sql2 += ")"; if (righe.size() - i > 1) sql2 += ", "; } sql2 += ";"; System.out.println(sql2); stmt.execute(sql); stmt.execute(sql2); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); } public static void main(String[] args) { } }
package com.jetbrains.jsonSchema; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.json.JsonBundle; import com.intellij.json.JsonFileType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ZipperUpdater; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileContentsChangedAdapter; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiTreeAnyChangeAbstractAdapter; import com.intellij.util.Alarm; import com.intellij.util.concurrency.SequentialTaskExecutor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.messages.Topic; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import com.jetbrains.jsonSchema.impl.JsonSchemaServiceImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.ExecutorService; /** * @author Irina.Chernushina on 3/30/2016. */ public final class JsonSchemaVfsListener extends BulkVirtualFileListenerAdapter { public static final Topic<Runnable> JSON_SCHEMA_CHANGED = Topic.create("JsonSchemaVfsListener.Json.Schema.Changed", Runnable.class); public static final Topic<Runnable> JSON_DEPS_CHANGED = Topic.create("JsonSchemaVfsListener.Json.Deps.Changed", Runnable.class); public static void startListening(@NotNull Project project, @NotNull JsonSchemaService service, @NotNull MessageBusConnection connection) { final MyUpdater updater = new MyUpdater(project, service); connection.subscribe(VirtualFileManager.VFS_CHANGES, new JsonSchemaVfsListener(updater)); PsiManager.getInstance(project).addPsiTreeChangeListener(new PsiTreeAnyChangeAbstractAdapter() { @Override protected void onChange(@Nullable PsiFile file) { if (file != null) updater.onFileChange(file.getViewProvider().getVirtualFile()); } }, (Disposable)service); } private JsonSchemaVfsListener(@NotNull MyUpdater updater) { super(new VirtualFileContentsChangedAdapter() { @NotNull private final MyUpdater myUpdater = updater; @Override protected void onFileChange(@NotNull final VirtualFile schemaFile) { myUpdater.onFileChange(schemaFile); } @Override protected void onBeforeFileChange(@NotNull VirtualFile schemaFile) { myUpdater.onFileChange(schemaFile); } }); } private static class MyUpdater { @NotNull private final Project myProject; private final ZipperUpdater myUpdater; @NotNull private final JsonSchemaService myService; private final Set<VirtualFile> myDirtySchemas = ContainerUtil.newConcurrentSet(); private final Runnable myRunnable; private final ExecutorService myTaskExecutor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor(JsonBundle.message( "json.vfs.updater.executor")); protected MyUpdater(@NotNull Project project, @NotNull JsonSchemaService service) { myProject = project; myUpdater = new ZipperUpdater(200, Alarm.ThreadToUse.POOLED_THREAD, (Disposable)service); myService = service; myRunnable = () -> { if (myProject.isDisposed()) return; Collection<VirtualFile> scope = new HashSet<>(myDirtySchemas); if (scope.stream().anyMatch(f -> service.possiblyHasReference(f.getName()))) { myProject.getMessageBus().syncPublisher(JSON_DEPS_CHANGED).run(); } myDirtySchemas.removeAll(scope); if (scope.isEmpty()) return; Collection<VirtualFile> finalScope = ContainerUtil.filter(scope, file -> myService.isApplicableToFile(file) && ((JsonSchemaServiceImpl)myService).isMappedSchema(file, false)); if (finalScope.isEmpty()) return; if (myProject.isDisposed()) return; myProject.getMessageBus().syncPublisher(JSON_SCHEMA_CHANGED).run(); final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(project); final PsiManager psiManager = PsiManager.getInstance(project); final Editor[] editors = EditorFactory.getInstance().getAllEditors(); Arrays.stream(editors).filter(editor -> editor instanceof EditorEx) .map(editor -> ((EditorEx)editor).getVirtualFile()) .filter(file -> file != null && file.isValid()) .forEach(file -> { final Collection<VirtualFile> schemaFiles = ((JsonSchemaServiceImpl)myService).getSchemasForFile(file, false, true); if (schemaFiles.stream().anyMatch(finalScope::contains)) { ReadAction.nonBlocking(() -> Optional.ofNullable(!psiManager.isDisposed() && file.isValid() ? psiManager.findFile(file) : null).ifPresent(analyzer::restart)).submit(myTaskExecutor); } }); }; } protected void onFileChange(@NotNull final VirtualFile schemaFile) { if (JsonFileType.DEFAULT_EXTENSION.equals(schemaFile.getExtension())) { myDirtySchemas.add(schemaFile); myUpdater.queue(myRunnable); } } } }
package it; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.model.MotechEvent; import org.motechproject.sms.api.service.SmsService; import org.motechproject.sms.smpp.ManagedSmslibService; import org.motechproject.sms.smpp.SmsSendHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import java.util.HashMap; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationSmsSmpp.xml"}) public class SendSmsIT { private SmsSendHandler smsSendHandler; @Autowired private ManagedSmslibService service; @Test @Ignore("run with smpp simulator; config in smpp.properties") public void shouldSendSms() throws Exception { smsSendHandler = new SmsSendHandler(service); MotechEvent event = new MotechEvent(SmsService.SEND_SMS, new HashMap<String, Object>() {{
package org.objectweb.proactive.api; import java.net.URI; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import org.objectweb.proactive.annotation.PublicAPI; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.remoteobject.RemoteObjectAdapter; import org.objectweb.proactive.core.remoteobject.RemoteObjectExposer; import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper; import org.objectweb.proactive.core.remoteobject.RemoteRemoteObject; import org.objectweb.proactive.core.remoteobject.adapter.Adapter; import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * This class provides methods to create, bind, lookup and unregister a remote object. * A 'Remote Object' is a standard java object that is remotely accessible through * all of the communication protocols supported by the ProActive's remote object framework. */ @PublicAPI public class PARemoteObject { public final static Logger logger = ProActiveLogger.getLogger(Loggers.REMOTEOBJECT); private final static String TURN_REMOTE_PREFIX; static { String vmName = ProActiveRuntimeImpl.getProActiveRuntime().getVMInformation().getName(); TURN_REMOTE_PREFIX = "/" + vmName + "/TURN_REMOTE/"; } private final static AtomicLong counter = new AtomicLong(); public static <T> RemoteObjectExposer<T> newRemoteObject(String className, T target) { return new RemoteObjectExposer<T>(className, target); } public static <T> RemoteObjectExposer<T> newRemoteObject(String className, T target, Class<? extends Adapter<T>> targetRemoteObjectAdapter) { return new RemoteObjectExposer<T>(className, target, targetRemoteObjectAdapter); } public static <T> T bind(RemoteObjectExposer<T> roe, URI uri) throws ProActiveException { RemoteRemoteObject irro = roe.createRemoteObject(uri); return (T) new RemoteObjectAdapter(irro).getObjectProxy(); } /** * List all the remote objects contained within a registry * @param url url of the registry * @return return the list of objects (not only remote objects) registered in the registry identified by the param url * @throws ProActiveException */ public static URI[] list(URI url) throws ProActiveException { return RemoteObjectHelper.getFactoryFromURL(url).list(RemoteObjectHelper.expandURI(url)); } /** * unregister the object located at the endpoint identified by the url * @param url * @throws ProActiveException */ public static void unregister(URI url) throws ProActiveException { RemoteObjectHelper.getFactoryFromURL(url).unregister(RemoteObjectHelper.expandURI(url)); } /** * perform a lookup on the url in order to retrieve a stub on the object exposed through * a remote object * @param url the url to lookup * @return a stub on the object exposed by the remote object * @throws ProActiveException */ public static Object lookup(URI url) throws ProActiveException { return RemoteObjectHelper.getFactoryFromURL(url).lookup(RemoteObjectHelper.expandURI(url)) .getObjectProxy(); } /** * Turn a POJO into a remote object. * * @param object the object to be exported as a remote object * @return A remote object that can be called from any JVM * @exception ProActiveException if the remote object cannot be created */ @SuppressWarnings("unchecked") public static <T> T turnRemote(T object) throws ProActiveException { RemoteObjectExposer<T> roe = newRemoteObject(object.getClass().getName(), object); RemoteRemoteObject rro = roe.createRemoteObject(TURN_REMOTE_PREFIX + counter.incrementAndGet()); return (T) new RemoteObjectAdapter(rro).getObjectProxy(); } }
package org.objectweb.proactive.core.ssh; import static org.objectweb.proactive.core.ssh.SSH.logger; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.objectweb.proactive.core.ssh.SshConfigFileParser.SshToken; import org.objectweb.proactive.core.ssh.proxycommand.SubnetChecker; /** * This class store all information read both in ssh configuration file * and in the PA_SSH_PROXY_GATEWAY PAProperties * */ public class SshConfig { private final static String defaultPath = System.getProperty("user.home") + File.separator + ".ssh" + File.separator; private final static String IPv4Regexp = "^.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; private final AtomicBoolean readOnly = new AtomicBoolean(false); private boolean tryPlainSocket; private boolean tryProxyCommand; private long gcInterval; private long gcIdleTime; private int connectTimeout; private String sshDirPath; /** * A Map of String and a Map of Token,String is used to represent the ssh configuration file, * information are stored for host (key of the global map table) and for each host, * each field of the ssh configuration file are represent by a SshToken in an inner map table * * easily extensible, only add a new token the SshToken, and fill, if special processing is needed, * the switch/case with the right method. */ private Map<String, Map<SshToken, String>> sshInfos; private SshToken[] capabilities = { SshToken.HOSTNAME, SshToken.USERNAME, SshToken.PORT, SshToken.PRIVATEKEY, SshToken.GATEWAY }; // Store here the mapping subnet / gateway private SubnetChecker subnetChecker = new SubnetChecker(); private String knownHostFile; private String keyDir; /** * This class represent all the information about ssh connection. * All fields have to be set, classicaly by using the SshConfigFileParser * * This constructor use the default path * * @see SshConfigFileParser * @see SshConnection */ public SshConfig() { this(defaultPath); } /** * This class represent all the information about ssh connection. * All fields have to be set, classically by using the SshConfigFileParser * * @param sshDirPath * The complete path to the directory where configuration file and * keys are placed * * @see SshConfigFileParser * @see SshConnection */ public SshConfig(String sshDirPath) { this.sshDirPath = sshDirPath; this.keyDir = sshDirPath; this.sshInfos = new Hashtable<String, Map<SshToken, String>>(); this.tryPlainSocket = false; this.tryProxyCommand = false; this.gcInterval = 5000; this.gcIdleTime = 10000; } /** * Method call by the parser to know which fields have to * be processed * * @return * A table of the SshTokens which represents wanted field * * @see SshConfigFileParser */ public SshToken[] getCapabilities() { return capabilities; } /** * This method store in the Maptable the <code> information </code> (gateway name, port, * username, ...) to use for contacting the host (<code> hostname </code>) * * If the information was already declared, then the new one is ignored * * @param hostname * The host to contact * * @param request * The field to set (username,port,gateway, ...) declare using an enum SshToken * * @param information * The value of the field * * * @see SshConfigFileParser */ public void addHostInformation(String hostname, SshToken request, String information) { if (hostname.charAt(0) == '*') { hostname = hostname.substring(1); } Map<SshToken, String> hostsInfos = sshInfos.get(hostname); if (hostsInfos == null) { // No information already record for the host hostsInfos = new Hashtable<SshToken, String>(); hostsInfos.put(request, information); sshInfos.put(hostname, hostsInfos); } else { if (hostsInfos.get(request) != null) { if (logger.isDebugEnabled()) { logger.debug("Ssh configuration : information " + information + " as " + request.toString().toLowerCase() + " for " + hostname + " is already declared, ignored"); } return; } hostsInfos.put(request, information); } if (logger.isDebugEnabled()) { logger.debug("Ssh configuration : " + information + " as " + request.toString().toLowerCase() + " stored for " + hostname); } } /** * Replace host by hostname in the map table because * ssh allow to use nickname in it configuration file * * @param host * nickname * * @param hostname * real host name * */ public void changeHostname(String host, String hostname) { Map<SshToken, String> infos = sshInfos.get(host); if (infos != null) { sshInfos.remove(host); sshInfos.put(hostname, infos); } } /** Seals the configuration */ final void setReadOnly() { this.readOnly.set(true); } final private void checkReadOnly() { if (this.readOnly.get()) throw new IllegalStateException(SshConfig.class.getName() + " bean is now read only, cannot be modified"); } // ACCESS METHOD // Default method /** * Do a wildcarded search in the maptable and return all the information * related to the machine <code> hostname </code> * * @param hostname * the name of the machine on which information are requested * @return * all information stored as a Map table of SshToken and String * */ public String getInformation(String hostname, SshToken tok) { if (tok.isWanted()) { Map<SshToken, String> hostInfos; int index; while (hostname.contains(".")) { hostInfos = sshInfos.get(hostname); if (hostInfos != null && hostInfos.get(tok) != null) { return hostInfos.get(tok); } else { // eat the first point hostname = hostname.substring(1); index = hostname.indexOf('.'); if (index < 0) break; hostname = hostname.substring(hostname.indexOf('.')); } } hostInfos = sshInfos.get(hostname); if (hostInfos != null && hostInfos.get(tok) != null) return hostInfos.get(tok); } return null; } /** * Never return null, if no information stored, return system username */ public String getUsername(String host) { String user = getInformation(host, SshToken.USERNAME); if (user == null) return System.getProperty("user.name"); return user; } /** * Return the hostname of the gateway to use to contact to host <code> hostname </code> * * @param host * The host to contact */ public String getGateway(String host) { String hostname = host; // Special case for protocol like RMI, which use ip address for answer if (host.matches(IPv4Regexp)) { String subnetTest = subnetChecker.getGateway(host); if (subnetTest != null) return subnetTest; } String gateway = getInformation(hostname, SshToken.GATEWAY); if (gateway == null || gateway.equalsIgnoreCase("none")) return null; return gateway; } /** * Never return null, if no information stored, return ssh default port : 22 */ public int getPort(String host) { String port = getInformation(host, SshToken.PORT); if (port != null) return Integer.parseInt(port); else return 22; } /** * Never return null, if no information stored, return ssh default private key */ public String[] getPrivateKeyPath(String host) throws IOException { String key = getInformation(host, SshToken.PRIVATEKEY); if (key != null) return new String[] { key }; else return new SSHKeys(getKeyDir()).getKeys(); } /** * Search the gateway to use for the host and return all rules related to this gateway */ public String getRule(String host) { String gateway = this.getInformation(host, SshToken.GATEWAY); StringBuilder sb = new StringBuilder(); // Add all rules defined by regular expression on hostname for this gateway for (String rule : sshInfos.keySet()) { String gatewayTest = sshInfos.get(rule).get(SshToken.GATEWAY); if (gatewayTest != null && gatewayTest.equalsIgnoreCase(gateway)) { sb.append(rule); sb.append(":"); sb.append(gateway); sb.append(":"); sb.append(getInformation(gateway, SshToken.PORT)); sb.append(";"); } } // Add all rules defined by ip address and cidr definition for this gateway for (String rule : subnetChecker.getRule(gateway).split(";")) { if (rule != null && !"".equals(rule.trim())) { sb.append(rule); sb.append(":"); sb.append(gateway); sb.append(":"); sb.append(getInformation(gateway, SshToken.PORT)); sb.append(";"); } } return sb.toString(); } /** * Store subnet definition */ public void addSubnetInformation(String subnet, String gateway) { checkReadOnly(); this.subnetChecker.setGateway(subnet, gateway); } // Classic getters and setters /** SSH tunnels and connections are garbage collected if unused longer than this amount of time (ms) */ public long getGcIdleTime() { return gcIdleTime; } public void setGcIdleTime(long gcIdleTime) { checkReadOnly(); this.gcIdleTime = gcIdleTime; } public boolean tryProxyCommand() { return tryProxyCommand; } public void setTryProxyCommand(boolean b) { checkReadOnly(); this.tryProxyCommand = b; } /** Should plain socket be used if direction is possible ? */ final public boolean tryPlainSocket() { checkReadOnly(); return tryPlainSocket; } final public void setTryPlainSocket(boolean tryNormalFirst) { checkReadOnly(); this.tryPlainSocket = tryNormalFirst; } /** The amount of time to wait between each garbage collection */ public long getGcInterval() { return gcInterval; } public void setGcInterval(long gcInterval) { checkReadOnly(); this.gcInterval = gcInterval; } /** The connect timeout for plain and ssh socket */ public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { checkReadOnly(); this.connectTimeout = connectTimeout; } public String getSshDirPath() { return sshDirPath; } public void setSshDirPath(String sshDirPath) { checkReadOnly(); this.sshDirPath = sshDirPath; } public void setKnowHostFile(String knownHostfile) { checkReadOnly(); this.knownHostFile = knownHostfile; } public String getKnowHostFile() { return this.knownHostFile; } public void setKeyDir(String keyDir) { checkReadOnly(); this.keyDir = keyDir; } public String getKeyDir() { return this.keyDir; } }
package som.interpreter.nodes; import som.interpreter.SArguments; import som.interpreter.TruffleCompiler; import som.interpreter.TypesGen; import som.interpreter.nodes.dispatch.AbstractDispatchNode; import som.interpreter.nodes.dispatch.GenericDispatchNode; import som.interpreter.nodes.dispatch.SuperDispatchNode; import som.interpreter.nodes.dispatch.UninitializedDispatchNode; import som.interpreter.nodes.literals.BlockNode; import som.interpreter.nodes.specialized.IfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueIfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueMessageNodeFactory; import som.interpreter.nodes.specialized.IntToDoMessageNodeFactory; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileFalseStaticBlocksNode; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileTrueStaticBlocksNode; import som.vm.Universe; import som.vmobjects.SBlock; import som.vmobjects.SSymbol; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.NodeInfo; public final class MessageSendNode { public static AbstractMessageSendNode create(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { return new UninitializedMessageSendNode(selector, receiver, arguments); } @NodeInfo(shortName = "send") public abstract static class AbstractMessageSendNode extends ExpressionNode implements PreevaluatedExpression { @Child protected ExpressionNode receiverNode; @Children protected final ExpressionNode[] argumentNodes; protected AbstractMessageSendNode(final ExpressionNode receiver, final ExpressionNode[] arguments) { this.receiverNode = adoptChild(receiver); this.argumentNodes = adoptChildren(arguments); } @Override public final Object executeGeneric(final VirtualFrame frame) { Object rcvr = receiverNode.executeGeneric(frame); Object[] arguments = evaluateArguments(frame); return executeEvaluated(frame, rcvr, arguments); } @ExplodeLoop private Object[] evaluateArguments(final VirtualFrame frame) { Object[] arguments = new Object[argumentNodes.length]; for (int i = 0; i < argumentNodes.length; i++) { arguments[i] = argumentNodes[i].executeGeneric(frame); } return arguments; } } private static final class UninitializedMessageSendNode extends AbstractMessageSendNode { private final SSymbol selector; protected UninitializedMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { super(receiver, arguments); this.selector = selector; } @Override public Object executeEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { return specialize(receiver, arguments).executeEvaluated(frame, receiver, arguments); } private PreevaluatedExpression specialize(final Object receiver, final Object[] arguments) { TruffleCompiler.transferToInterpreterAndInvalidate("Specialize Message Node"); // first option is a super send, super sends are treated specially because // the receiver class is lexically determined if (receiverNode instanceof ISuperReadNode) { GenericMessageSendNode node = new GenericMessageSendNode(selector, receiverNode, argumentNodes, SuperDispatchNode.create(selector, (ISuperReadNode) receiverNode)); return replace(node); } // We treat super sends separately for simplicity, might not be the // optimal solution, especially in cases were the knowledge of the // receiver class also allows us to do more specific things, but for the // moment we will leave it at this. // TODO: revisit, and also do more specific optimizations for super sends. // let's organize the specializations by number of arguments // perhaps not the best, but one simple way to just get some order into // the chaos. switch (argumentNodes.length) { // case 0: return specializeUnary( receiver, arguments); // don't have any at the moment case 1: return specializeBinary(receiver, arguments); case 2: return specializeTernary(receiver, arguments); } return makeGenericSend(); } private GenericMessageSendNode makeGenericSend() { GenericMessageSendNode send = new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); return replace(send); } private PreevaluatedExpression specializeBinary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "whileTrue:": { if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileTrueStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send } case "whileFalse:": if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileFalseStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send case "ifTrue:": return replace(IfTrueMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); case "ifFalse:": return replace(IfFalseMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); } return makeGenericSend(); } private PreevaluatedExpression specializeTernary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "ifTrue:ifFalse:": return replace(IfTrueIfFalseMessageNodeFactory.create(receiver, arguments[0], arguments[1], Universe.current(), receiverNode, argumentNodes[0], argumentNodes[1])); case "to:do:": if (TypesGen.TYPES.isImplicitInteger(receiver) && TypesGen.TYPES.isImplicitInteger(arguments[0]) && TypesGen.TYPES.isSBlock(arguments[1])) { return replace(IntToDoMessageNodeFactory.create(this, (SBlock) arguments[1], receiverNode, argumentNodes[0], argumentNodes[1])); } break; } return makeGenericSend(); } } public static final class GenericMessageSendNode extends AbstractMessageSendNode { public static GenericMessageSendNode create(final SSymbol selector, final ExpressionNode receiverNode, final ExpressionNode[] argumentNodes) { return new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); } @Child private AbstractDispatchNode dispatchNode; private GenericMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments, final AbstractDispatchNode dispatchNode) { super(receiver, arguments); this.dispatchNode = adoptChild(dispatchNode); } @Override public Object executeEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { SArguments args = new SArguments(receiver, arguments); return dispatchNode.executeDispatch(frame, args); } public void replaceDispatchNodeBecauseCallSiteIsMegaMorphic( final GenericDispatchNode replacement) { dispatchNode.replace(replacement); } } }
package chabu.tester; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayDeque; import java.util.Iterator; import java.util.Set; import java.util.TreeMap; import chabu.INetwork; import chabu.INetworkUser; import chabu.Utils; import chabu.tester.data.ACommand; import chabu.tester.data.AResult; import chabu.tester.data.AXferItem; import chabu.tester.data.CmdDutConnect; import chabu.tester.data.CmdDutDisconnect; public class ChabuTestNw { private String name; private boolean doShutDown; private Selector selector; private CtrlNetwork ctrlNw = new CtrlNetwork(); private Thread thread; private boolean isStarted = false; private TreeMap<DutId, DutState> dutStates = new TreeMap<>(); class DutState { final ByteBuffer txBuffer; final ArrayDeque<ACommand> commands; public SocketChannel socketChannel; int registeredInterrestOps = 0; public ByteBuffer rxBuffer; DutState(){ commands = new ArrayDeque<>(100); txBuffer = ByteBuffer.allocate(2000); rxBuffer = ByteBuffer.allocate(2000); txBuffer.clear(); rxBuffer.clear(); } public void addCommand(ACommand cmd) throws ClosedChannelException { commands.add(cmd); if( (registeredInterrestOps & SelectionKey.OP_WRITE) == 0 ){ selector.wakeup(); registeredInterrestOps |= SelectionKey.OP_WRITE; socketChannel.register( selector, registeredInterrestOps, this ); } } } class CtrlNetwork extends Network { } class Network implements INetwork { // ServerSocketChannel serverSocket; // SocketChannel socketChannel; ByteBuffer rxBuffer = ByteBuffer.allocate(0x10000); ByteBuffer txBuffer = ByteBuffer.allocate(0x10000); INetworkUser user; boolean userRequestRecv = false; boolean userRequestXmit = false; boolean netwRequestRecv = true; boolean netwRequestXmit = true; Network(){ rxBuffer.position(rxBuffer.limit()); } public void setNetworkUser(INetworkUser user) { this.user = user; } public void evUserXmitRequest() { userRequestXmit = true; netwRequestRecv = true; selector.wakeup(); } public void evUserRecvRequest() { userRequestRecv = true; netwRequestXmit = true; selector.wakeup(); } public void handleRequests() { if( userRequestRecv ){ userRequestRecv = false; user.evRecv(rxBuffer); } if( userRequestXmit ){ userRequestXmit = false; user.evXmit(txBuffer); } } // public void connectionClose() throws IOException { // socketChannel.close(); }; public void setCtrlNetworkUser(INetworkUser user) { this.ctrlNw.user = user; } public ChabuTestNw(String name) throws IOException, InterruptedException { this.name = name; selector = Selector.open(); // ctrlNw.serverSocket = ServerSocketChannel.open(); // ctrlNw.serverSocket.configureBlocking(false); // ctrlNw.serverSocket.register( selector, 0 ); thread = new Thread( this::run, name ); thread.start(); synchronized(this){ while( !isStarted ){ this.wait(); } } } private void run() { try { @SuppressWarnings("unused") int connectionOpenIndex = 0; synchronized(this){ isStarted = true; notifyAll(); } while (!doShutDown) { // System.out.printf("%s: selector sleep\n", name ); selector.select(); // System.out.printf("%s: selector wakeup\n", name ); Set<SelectionKey> readyKeys = selector.selectedKeys(); ctrlNw.handleRequests(); Iterator<SelectionKey> iterator = readyKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); iterator.remove(); // System.out.printf("%s selector key %s\n", name, key); if( key.isValid() ){ if (key.isConnectable()) { // System.out.printf("%s: connecting\n", name ); synchronized( this ){ DutState ds = (DutState)key.attachment(); if (ds.socketChannel.isConnectionPending()){ if( ds.socketChannel.finishConnect() ){ ds.registeredInterrestOps &= ~SelectionKey.OP_CONNECT; ds.registeredInterrestOps |= SelectionKey.OP_READ; ds.socketChannel.register( selector, ds.registeredInterrestOps, ds ); System.out.printf("%s: connecting ok\n", name ); } } } } if (key.isWritable() ) { synchronized( this ){ DutState ds = (DutState)key.attachment(); // System.out.printf("Tester %s: write p1\n", name ); while( ds.txBuffer.remaining() > 1000 && !ds.commands.isEmpty() ){ //System.out.printf("Tester %s: loop buf %s\n", name, ds.txBuffer ); ACommand cmd = ds.commands.remove(); AXferItem.encodeItem(ds.txBuffer, cmd); } // System.out.printf("Tester %s: buf %s\n", name, ds.txBuffer ); ds.txBuffer.flip(); // System.out.printf("Tester %s: write %s bytes\n", name, ds.txBuffer.remaining() ); ds.socketChannel.write(ds.txBuffer); if( ds.commands.isEmpty() && !ds.txBuffer.hasRemaining() ){ this.notifyAll(); } if( !ds.txBuffer.hasRemaining() ){ ds.registeredInterrestOps &= ~SelectionKey.OP_WRITE; ds.socketChannel.register( selector, ds.registeredInterrestOps, ds ); } ds.txBuffer.compact(); this.notifyAll(); } } if( key.isReadable() ){ synchronized( this ){ DutState ds = (DutState)key.attachment(); int readSz = ds.socketChannel.read( ds.rxBuffer ); // System.out.printf("%s read %d\n", name, readSz ); ds.rxBuffer.flip(); while( ds.rxBuffer.hasRemaining() ){ AResult res = AResult.decodeResult(ds.rxBuffer); if( res == null ) { break; } consumeResult( res ); } ds.rxBuffer.compact(); if( readSz < 0 ){ ds.socketChannel.close(); System.out.printf("%s closed\n", name ); } } } } } } } catch (Exception e) { e.printStackTrace(); } finally { try { synchronized(this){ for( DutState ds : dutStates.values() ){ if( ds.socketChannel != null ){ ds.socketChannel.close(); ds.socketChannel = null; } } dutStates.clear(); } if( selector != null ) { selector.close(); } synchronized( this ){ notifyAll(); } } catch (Exception e) { e.printStackTrace(); } } } private void consumeResult(AResult res) { System.out.printf("%s: recv %s\n", name, res ); } public void start() { Utils.ensure( thread == null ); thread = new Thread(this::run); thread.start(); } public void shutDown() { doShutDown = true; selector.wakeup(); } public synchronized void forceShutDown() { shutDown(); while( selector.isOpen() ){ Utils.waitOn(this); } } public synchronized void addCommand(DutId dut, ACommand cmd) throws IOException { if( dut == DutId.ALL ){ Utils.ensure( !(cmd instanceof CmdDutConnect) ); Utils.ensure( !(cmd instanceof CmdDutDisconnect) ); for( DutState ds : dutStates.values() ){ ds.addCommand( cmd ); } } else { if( !dutStates.containsKey(dut)){ dutStates.put( dut, new DutState()); } DutState ds = dutStates.get(dut); if( cmd instanceof CmdDutConnect ){ Utils.ensure( ds.socketChannel == null ); CmdDutConnect cmdDutConnect = (CmdDutConnect)cmd; SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect( new InetSocketAddress( cmdDutConnect.address, cmdDutConnect.port )); ds.socketChannel = socketChannel; ds.registeredInterrestOps = SelectionKey.OP_CONNECT; selector.wakeup(); socketChannel.register( selector, ds.registeredInterrestOps, ds ); System.out.println("selector wakeup!"); } else if( cmd instanceof CmdDutDisconnect ){ if( ds.socketChannel != null ) { ds.socketChannel.close(); } } else { ds.addCommand( cmd ); } } notifyAll(); } public synchronized void flush( DutId dut ) throws InterruptedException { while(true){ boolean isEmpty = true; if( dut == DutId.ALL ){ for( DutState ds : dutStates.values() ){ if( !ds.commands.isEmpty() ){ isEmpty = false; } } } else { DutState ds = dutStates.get(dut); if( ds != null && !ds.commands.isEmpty() ){ isEmpty = false; } } if( isEmpty ){ break; } wait(); } } }
package groovy.io; import groovy.text.SimpleTemplateEngine; import groovy.text.Template; import junit.framework.TestCase; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class PlatformLineWriterTest extends TestCase { public void testPlatformLineWriter() throws IOException, ClassNotFoundException { String LS = System.getProperty("line.separator"); Map binding = new HashMap(); binding.put("first", "Tom"); binding.put("last", "Adams"); Template template = new SimpleTemplateEngine().createTemplate("<%= first %>\n<% println last %>"); StringWriter stringWriter = new StringWriter(); Writer platformWriter = new PlatformLineWriter(stringWriter); template.make(binding).writeTo(platformWriter); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); } }
package com.javax0.jdsl; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.javax0.jdsl.analyzers.AnalysisResult; import com.javax0.jdsl.analyzers.Analyzer; import com.javax0.jdsl.analyzers.PassThroughAnalyzer; import com.javax0.jdsl.analyzers.StringSourceCode; import com.javax0.jdsl.executors.Executor; import com.javax0.jdsl.executors.Factory; import com.javax0.jdsl.executors.ListExecutor; public class GrammarTest { @Test public void given_SimpleGrammarAndMatchingSource_when_Analyzing_then_Success() { Analyzer ifGrammar = new GrammarDefinition() { @Override void define() { // skipSpaces(); PassThroughAnalyzer command = definedLater("command"); PassThroughAnalyzer expression = definedLater("expression"); Analyzer ifStatement = list(new IfExecutorFactory(), kw("if", "("), expression, kw(")", "{"), command, kw("}"), optional(kw("else", "{"), command, kw("}"))); expression.define(number()); command.define(or(ifStatement, kw("A", ";"), kw("B", ";"), list(number(), kw(";")), list(kw("{"), many(command), kw("}")))); grammar = many(command); } }; AnalysisResult result; Long res; // result = ifGrammar.analyze(new StringSourceCode( // "if(1){55;} else{33;}")); // res = (Long)result.getExecutor().execute(); // Assert.assertEquals((Long)55L, res); // result = ifGrammar.analyze(new StringSourceCode( // "if(1){55;}")); // res = (Long)result.getExecutor().execute(); // Assert.assertEquals((Long)55L, res); result = ifGrammar.analyze(new StringSourceCode( "if(1){if(0){1;}else{55;}}")); Object resO = result.getExecutor().execute(); // Assert.assertEquals((Long)55L, res); } private static class IfExecutorFactory implements Factory<ListExecutor> { @Override public ListExecutor get() { return new IfExecutor(); } } private static class IfExecutor implements ListExecutor { @Override public Object execute() { Object condition = executorList.get(0).execute(); Long one = (Long) condition; if (one != 0) { if (executorList.size() > 1) { return executorList.get(1).execute(); } else { return null; } } else { if (executorList.size() > 2) { return executorList.get(2).execute(); } else { return null; } } } private List<Executor> executorList; @Override public void setList(List<Executor> executorList) { this.executorList = executorList; } } }
package org.biojava.bio.dp; import java.util.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; public abstract class DP { public static MarkovModel flatView(MarkovModel model) throws IllegalAlphabetException, IllegalSymbolException { for(Iterator i = model.stateAlphabet().iterator(); i.hasNext(); ) { State s = (State) i.next(); if( !(s instanceof DotState) || !(s instanceof EmissionState) ) { return new FlatModel(model); } } return model; } public static State[] stateList(MarkovModel mm) throws IllegalSymbolException, IllegalTransitionException, BioException { FiniteAlphabet alpha = mm.stateAlphabet(); List emissionStates = new ArrayList(); HMMOrderByTransition comp = new HMMOrderByTransition(mm); List dotStates = new LinkedList(); for (Iterator addStates = alpha.iterator(); addStates.hasNext(); ) { Object state = addStates.next(); if (state instanceof EmissionState) { emissionStates.add(state); } else { ListIterator checkOld = dotStates.listIterator(); int insertPos = -1; while (checkOld.hasNext() && insertPos == -1) { Object oldState = checkOld.next(); if (comp.compare(state, oldState) == comp.LESS_THAN) { insertPos = checkOld.nextIndex() - 1; } } if (insertPos >= 0) { dotStates.add(insertPos, state); } else { dotStates.add(state); } } } State[] sl = new State[emissionStates.size() + dotStates.size()]; int i = 0; for (Iterator si = emissionStates.iterator(); si.hasNext(); ) { EmissionState ex = (EmissionState) si.next(); int [] ad = ex.getAdvance(); if(ad.length != mm.heads()) { throw new BioException( "Advance (" + ad.length + ") is not the same size as the number of heads (" + mm.heads() + " for state " + ex.getName() + " in model " + mm.stateAlphabet().getName() ); } for(int adi = 0; ad != null && adi < ad.length; adi++) { if(ad[adi] != 0) { ad = null; } } if(ad != null) { throw new Error( "State " + ex.getName() + " has advance " + ad ); } sl[i++] = ex; } for (Iterator si = dotStates.iterator(); si.hasNext(); ) { sl[i++] = (State) si.next(); } return sl; } private static class HMMOrderByTransition { public final static Object GREATER_THAN = new Object(); public final static Object LESS_THAN = new Object(); public final static Object EQUAL = new Object(); public final static Object DISJOINT = new Object(); private MarkovModel mm; HMMOrderByTransition(MarkovModel mm) { this.mm = mm; } public Object compare(Object o1, Object o2) throws IllegalTransitionException, IllegalSymbolException { if (o1 == o2) { return EQUAL; } State s1 = (State) o1; State s2 = (State) o2; if (transitionsTo(s1, s2)) { return LESS_THAN; } if (transitionsTo(s2, s1)) { return GREATER_THAN; } return DISJOINT; } private boolean transitionsTo(State from, State to) throws IllegalTransitionException, IllegalSymbolException { Set checkedSet = new HashSet(); Set workingSet = mm.transitionsFrom(from); while (workingSet.size() > 0) { Set newWorkingSet = new HashSet(); for (Iterator i = workingSet.iterator(); i.hasNext(); ) { State s = (State) i.next(); if (s instanceof EmissionState) { continue; } if (s == from) { throw new IllegalTransitionException( from, from, "Loop in dot states." ); } if (s == to) { return true; } for (Iterator j = mm.transitionsFrom(s).iterator(); j.hasNext(); ) { State s2 = (State) j.next(); if (!workingSet.contains(s2) && !checkedSet.contains(s2)) { newWorkingSet.add(s2); } } checkedSet.add(s); } workingSet = newWorkingSet; } return false; } } public static int [][] forwardTransitions( MarkovModel model, State [] states ) throws IllegalSymbolException { int stateCount = states.length; int [][] transitions = new int[stateCount][]; for (int i = 0; i < stateCount; i++) { int [] tmp = new int[stateCount]; int len = 0; Set trans = model.transitionsTo(states[i]); for (int j = 0; j < stateCount; j++) { if (trans.contains(states[j])) { tmp[len++] = j; } } int [] tmp2 = new int[len]; for (int j = 0; j < len; j++) tmp2[j] = tmp[j]; transitions[i] = tmp2; } return transitions; } public static double [][] forwardTransitionScores( MarkovModel model, State [] states, int [][] transitions ) throws IllegalSymbolException { int stateCount = states.length; double [][] scores = new double[stateCount][]; for (int i = 0; i < stateCount; i++) { State is = states[i]; scores[i] = new double[transitions[i].length]; for (int j = 0; j < scores[i].length; j++) { try { scores[i][j] = model.getTransitionScore(states[transitions[i][j]], is); } catch (IllegalTransitionException ite) { throw new BioError(ite, "Transition listed in transitions array has dissapeared."); } } } return scores; } public static int [][] backwardTransitions(MarkovModel model, State [] states) throws IllegalSymbolException { int stateCount = states.length; int [][] transitions = new int[stateCount][]; for (int i = 0; i < stateCount; i++) { int [] tmp = new int[stateCount]; int len = 0; Set trans = model.transitionsFrom(states[i]); for (int j = 0; j < stateCount; j++) { if (trans.contains(states[j])) tmp[len++] = j; } int [] tmp2 = new int[len]; for (int j = 0; j < len; j++) tmp2[j] = tmp[j]; transitions[i] = tmp2; } return transitions; } public static double [][] backwardTransitionScores(MarkovModel model, State [] states, int [][] transitions) throws IllegalSymbolException { int stateCount = states.length; double [][] scores = new double[stateCount][]; for (int i = 0; i < stateCount; i++) { State is = states[i]; scores[i] = new double[transitions[i].length]; for (int j = 0; j < scores[i].length; j++) { try { scores[i][j] = model.getTransitionScore(is, states[transitions[i][j]]); } catch (IllegalTransitionException ite) { throw new BioError(ite, "Transition listed in transitions array has dissapeared"); } } } return scores; } private MarkovModel model; private State[] states; private int [][] forwardTransitions; private double [][] forwardTransitionScores; private int [][] backwardTransitions; private double [][] backwardTransitionScores; private int dotStatesIndex; public int getDotStatesIndex() { return dotStatesIndex; } public MarkovModel getModel() { return model; } public State[] getStates() { return states; } public int [][] getForwardTransitions() { return forwardTransitions; } public double [][] getForwardTransitionScores() { return forwardTransitionScores; } public int [][] getBackwardTransitions() { return backwardTransitions; } public double [][] getBackwardTransitionScores() { return backwardTransitionScores; } public DP(MarkovModel model) throws IllegalSymbolException, IllegalTransitionException, BioException { this.model = model; validate(); } /** * Revalidate the DP object after a change in the underlying * MarkovModel. The main effect is to rebuild the DP object's * internal table of transition probabilities. */ public void validate() throws IllegalSymbolException, IllegalTransitionException, BioException { this.states = stateList(model); this.forwardTransitions = forwardTransitions(model, states); this.forwardTransitionScores = forwardTransitionScores(model, states, forwardTransitions); this.backwardTransitions = backwardTransitions(model, states); this.backwardTransitionScores = backwardTransitionScores(model, states, backwardTransitions); // Find first dot state int i; for (i = 0; i < states.length; ++i) { if (! (states[i] instanceof EmissionState)) break; } dotStatesIndex = i; } public abstract double forward(SymbolList [] resList) throws IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract double backward(SymbolList [] resList) throws IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract DPMatrix forwardMatrix(SymbolList [] resList) throws IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract DPMatrix backwardMatrix(SymbolList [] resList) throws IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract DPMatrix forwardMatrix(SymbolList [] resList, DPMatrix matrix) throws IllegalArgumentException, IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract DPMatrix backwardMatrix(SymbolList [] resList, DPMatrix matrix) throws IllegalArgumentException, IllegalSymbolException, IllegalAlphabetException, IllegalTransitionException; public abstract StatePath viterbi(SymbolList [] resList) throws IllegalSymbolException, IllegalArgumentException, IllegalAlphabetException, IllegalTransitionException; public DPMatrix forwardsBackwards(SymbolList [] resList) throws BioException { try { System.out.println("Making backward matrix"); final DPMatrix bMatrix = backwardMatrix(resList); System.out.println("Making forward matrix"); final DPMatrix fMatrix = forwardMatrix(resList); System.out.println("Making forward/backward matrix"); return new DPMatrix() { public double getCell(int [] index) { return fMatrix.getCell(index) + bMatrix.getCell(index); } public double getScore() { return fMatrix.getScore(); } public MarkovModel model() { return fMatrix.model(); } public SymbolList [] resList() { return fMatrix.resList(); } public State [] states() { return fMatrix.states(); } }; } catch (Exception e) { throw new BioException(e, "Couldn't build forwards-backwards matrix"); } } /** * Generates an alignment from a model. * <P> * If the length is set to -1 then the model length will be sampled * using the model's transition to the end state. If the length is * fixed using length, then the transitions to the end state are implicitly * invoked. * * @param length the length of the sequence to generate * @return a StatePath generated at random */ public StatePath generate(int length) throws IllegalSymbolException, BioException { List scoreList = new ArrayList(); SimpleSymbolList tokens = new SimpleSymbolList(model.emissionAlphabet()); SimpleSymbolList states = new SimpleSymbolList(model.stateAlphabet()); double totScore = 0.0; double resScore = 0.0; int i = length; State oldState; Symbol token; oldState = model.sampleTransition(model.magicalState()); try { resScore += model.getTransitionScore(model.magicalState(), oldState); } catch (IllegalTransitionException ite) { throw new BioError(ite, "Transition returned from sampleTransition is invalid"); } DoubleAlphabet dAlpha = DoubleAlphabet.getInstance(); if (oldState instanceof EmissionState) { EmissionState eState = (EmissionState) oldState; token = eState.sampleSymbol(); resScore += eState.getWeight(token); states.addSymbol(oldState); tokens.addSymbol(token); scoreList.add(dAlpha.getSymbol(resScore)); totScore += resScore; resScore = 0.0; i } while (i != 0) { State newState; do { newState = model.sampleTransition(oldState); } while (newState == model.magicalState() && i > 0); try { resScore += model.getTransitionScore(oldState, newState); } catch (IllegalTransitionException ite) { throw new BioError(ite, "Transition returned from sampleTransition is invalid"); } if (newState == model.magicalState()) { break; } if (newState instanceof EmissionState) { EmissionState eState = (EmissionState) newState; token = eState.sampleSymbol(); resScore += eState.getWeight(token); states.addSymbol(newState); tokens.addSymbol(token); scoreList.add(dAlpha.getSymbol(resScore)); totScore += resScore; resScore = 0.0; i } oldState = newState; } List resListList = new ArrayList(3); resListList.add(tokens); resListList.add(states); resListList.add(new SimpleSymbolList(dAlpha, scoreList)); Map labelToResList = new HashMap(); labelToResList.put(StatePath.SEQUENCE, tokens); labelToResList.put(StatePath.STATES, states); labelToResList.put(StatePath.SCORES, new SimpleSymbolList(dAlpha, scoreList)); return new SimpleStatePath(totScore, labelToResList); } public static class ReverseIterator implements Iterator { private SymbolList res; private int index; public ReverseIterator(SymbolList res) { this.res = res; index = res.length(); } public boolean hasNext() { return index > 0; } public Object next() { return res.symbolAt(index } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("This itterator can not cause modifications"); } } }
package com.pful.pico.db; import com.pful.pico.Service; import io.vertx.core.Vertx; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.CountDownLatch; import static com.pful.pico.db.Finder.Field.field; public class FinderTest { private static Vertx vertx; @BeforeClass public static void startMongoDB() { vertx = Vertx.vertx(); vertx.deployVerticle(Service.class.getName()); } @AfterClass public static void stopMongoDb() { vertx.close(); } @Test public void queryTest() { final CountDownLatch latch = new CountDownLatch(1); final Finder builder = new Finder(); builder.field("name").is("111") .inCollection("Entities") .execute((results) -> { System.out.println(results.result()); latch.countDown(); }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void queryTest2() { Finder.open() .allOf( field("a").is("F"), field("b").is("V")) .and() .field("").is("A") .and() .field("c").is("G") .inCollection("") .execute(results -> { }); } @Test public void queryTest3() { Finder.open() .inCollection("") .execute(result -> { }); } @Test public void queryTest4() { Finder.open() .allOf( field("A").is("a") ) .inCollection("") .execute(results -> { }); } @Test public void queryTest5() { //{ $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } Finder.open() .allOf( field("price").ne(1.99), field("price").exists(true) ) .inCollection("") .execute(result -> { }); Finder.open() .field("price") .ne(1.99) .and() .field("price") .exists(true) .inCollection("") .execute(results -> { }); } @Test public void queryTest6() { // { $and : [{ qty : {$in : [5, 15]}}, { tags : { $in : ["appliance", "school"]}}]} Finder.open() .field("qty") .in(5, 15) .and() .field("tags") .in("appliances", "school") .inCollection("A") .execute(results -> { }); } @Test public void queryTest7() { // price: { $not: { $gt: 1.99 } } } Finder.open() .field("price") .lte(1.99) .inCollection("A") .execute(results -> { }); } @Test public void queryTest8() { // { $and : [ // { $or : [ { price : 0.99 }, { price : 1.99 } ] }, // { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } Finder.open() .anyOf( field("price").is(0.99), field("price").is(1.99) ) .and() .anyOf( field("sale").is(true), field("qty").lt(20) ) .inCollection("") .execute(results -> { }); } }
package org.broad.igv.ui; import com.jidesoft.plaf.LookAndFeelFactory; import jargs.gnu.CmdLineParser; import htsjdk.samtools.seekablestream.SeekableStreamFactory; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.ui.event.GlobalKeyDispatcher; import org.broad.igv.util.HttpUtils; import org.broad.igv.util.RuntimeUtils; import org.broad.igv.util.stream.IGVSeekableStreamFactory; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; import java.util.Arrays; import java.util.HashSet; /** * Utility class for launching IGV. Provides a "main" method and an "open" method for opening IGV in a supplied Frame. * <p/> * Note: The "open" methods must be executed on the event thread, for example * <p/> * public static void main(String[] args) { * EventQueue.invokeLater(new Runnable() { * public void run() { * Frame frame = new Frame(); * org.broad.igv.ui.Main.open(frame); * } * ); * } * * @author jrobinso * @date Feb 7, 2011 */ public class Main { private static Logger log = Logger.getLogger(Main.class); /** * Launch an igv instance as a stand-alone application in its own Frame. * * @param args */ public static void main(final String args[]) { Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler()); initApplication(); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon icon = new ImageIcon(Main.class.getResource("mainframeicon.png")); if (icon != null) frame.setIconImage(icon.getImage()); open(frame, args); } private static void initApplication() { long mem = RuntimeUtils.getAvailableMemory(); int MB = 1000000; if (mem < 400 * MB) { int mb = (int) (mem / MB); JOptionPane.showMessageDialog(null, "Warning: IGV is running with minimal available memory (" + mb + " mb)"); } DirectoryManager.initializeLog(); log.info("Startup " + Globals.applicationString()); log.info("Java " + System.getProperty(Globals.JAVA_VERSION_STRING)); log.info("Default User Directory: " + DirectoryManager.getUserDirectory()); log.info("OS: " + System.getProperty("os.name")); System.setProperty("http.agent", Globals.applicationString()); Runtime.getRuntime().addShutdownHook(new ShutdownThread()); updateTooltipSettings(); System.setProperty ("jsse.enableSNIExtension", "false"); // Anti alias settings. TODO = Are these neccessary anymore ? System.setProperty("awt.useSystemAAFontSettings", "on"); System.setProperty("swing.aatext", "true"); checkVersion(); } public static void updateTooltipSettings() { ToolTipManager.sharedInstance().setEnabled(true); final PreferenceManager prefMgr = PreferenceManager.getInstance(); ToolTipManager.sharedInstance().setInitialDelay(prefMgr.getAsInt(PreferenceManager.TOOLTIP_INITIAL_DELAY)); ToolTipManager.sharedInstance().setReshowDelay(prefMgr.getAsInt(PreferenceManager.TOOLTIP_RESHOW_DELAY)); ToolTipManager.sharedInstance().setDismissDelay(prefMgr.getAsInt(PreferenceManager.TOOLTIP_DISMISS_DELAY)); } private static void checkVersion() { int readTimeout = Globals.READ_TIMEOUT; int connectTimeout = Globals.CONNECT_TIMEOUT; try { Version thisVersion = Version.getVersion(Globals.VERSION); if (thisVersion == null) return; // Can't compare Globals.CONNECT_TIMEOUT = 5000; Globals.READ_TIMEOUT = 1000; final String serverVersionString = HttpUtils.getInstance().getContentsAsString(new URL(Globals.getVersionURL())).trim(); // See if user has specified to skip this update final String skipString = PreferenceManager.getInstance().get(PreferenceManager.SKIP_VERSION); HashSet<String> skipVersion = new HashSet<String>(Arrays.asList(skipString.split(","))); if (skipVersion.contains(serverVersionString)) return; Version serverVersion = Version.getVersion(serverVersionString.trim()); if(serverVersion == null) return; if (thisVersion.lessThan(serverVersion)) { final VersionUpdateDialog dlg = new VersionUpdateDialog(serverVersionString); SwingUtilities.invokeAndWait(new Runnable() { public void run() { dlg.setVisible(true); if (dlg.isSkipVersion()) { String newSkipString = skipString + "," + serverVersionString; PreferenceManager.getInstance().put(PreferenceManager.SKIP_VERSION, newSkipString); } } }); } } catch (Exception e) { log.error("Error checking version", e); } finally { Globals.CONNECT_TIMEOUT = connectTimeout; Globals.READ_TIMEOUT = readTimeout; } } /** * Open an IGV instance in the supplied Frame. * * @param frame */ public static void open(Frame frame) { open(frame, new String[]{}); } /** * Open an IGV instance in the supplied frame. * * @param frame * @param args command-line arguments */ public static void open(Frame frame, String[] args) { // Add a listener for the "close" icon, unless its a JFrame if (!(frame instanceof JFrame)) { frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { windowEvent.getComponent().setVisible(false); } }); } // Turn on tooltip in case it was disabled for a temporary keyboard event, e.g. alt-tab frame.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { ToolTipManager.sharedInstance().setEnabled(true); } @Override public void windowGainedFocus(WindowEvent windowEvent) { this.windowActivated(windowEvent); } }); initializeLookAndFeel(); Main.IGVArgs igvArgs = new Main.IGVArgs(args); // Optional arguments if (igvArgs.getPropertyOverrides() != null) { PreferenceManager.getInstance().loadOverrides(igvArgs.getPropertyOverrides()); } if (igvArgs.getDataServerURL() != null) { PreferenceManager.getInstance().overrideDataServerURL(igvArgs.getDataServerURL()); } if (igvArgs.getGenomeServerURL() != null) { PreferenceManager.getInstance().overrideGenomeServerURL(igvArgs.getGenomeServerURL()); } HttpUtils.getInstance().updateProxySettings(); //AbstractFeatureReader.setComponentMethods(new IGVComponentMethods()); SeekableStreamFactory.setInstance(IGVSeekableStreamFactory.getInstance()); RuntimeUtils.loadPluginJars(); IGV.createInstance(frame).startUp(igvArgs); // TODO Should this be done here? Will this step on other key dispatchers? KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new GlobalKeyDispatcher()); } private static void initializeLookAndFeel() { try { String lnf = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(lnf); } catch (Exception e) { e.printStackTrace(); } if (Globals.IS_LINUX) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); UIManager.put("JideSplitPane.dividerSize", 5); UIManager.put("JideSplitPaneDivider.background", Color.darkGray); } catch (Exception exception) { exception.printStackTrace(); } } // Todo -- what does this do? LookAndFeelFactory.installJideExtension(); } /** * Class to represent the IGV version. The version numbering follows Microsoft conventions. This class is public * to allow unit tests. * <p/> * Example internal version string: 2.3.27 (31)02/18/2014 11:42 PM * Example server version string: 2.3.27 */ public static class Version { private int major; private int minor; private int build; public static Version getVersion(String versionString) { String[] tokens = versionString.split("\\."); if (tokens.length < 2) { return null; // Unknown version } else { try { int major = Integer.parseInt(tokens[0]); int minor = Integer.parseInt(tokens[1]); int build = tokens.length <= 2 ? 0 : Integer.parseInt(tokens[2]); return new Version(major, minor, build); } catch (NumberFormatException e) { log.error("Error parsing version string: " + versionString); return null; } } } private Version(int major, int minor, int build) { this.major = major; this.minor = minor; this.build = build; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getBuild() { return build; } public boolean lessThan(Version anotherVersion) { if (anotherVersion.major > this.major) return true; else if (anotherVersion.major < this.major) return false; else if (anotherVersion.minor > this.minor) return true; else if (anotherVersion.minor < this.minor) return false; else return anotherVersion.build > this.build; } } /** * Class to encapsulate IGV command line arguments. */ static public class IGVArgs { private String batchFile = null; private String sessionFile = null; private String dataFileString = null; private String locusString = null; private String propertyOverrides = null; private String genomeId = null; private String port = null; private String dataServerURL = null; private String genomeServerURL = null; private String indexFile = null; private String coverageFile = null; private String name = null; IGVArgs(String[] args) { if (args != null) { parseArgs(args); } } /** * Parse arguments. All arguments are optional, a full set of arguments are * firstArg locusString -b batchFile -p preferences */ private void parseArgs(String[] args) { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option propertyFileOption = parser.addStringOption('o', "preferences"); CmdLineParser.Option batchFileOption = parser.addStringOption('b', "batch"); CmdLineParser.Option portOption = parser.addStringOption('p', "port"); CmdLineParser.Option genomeOption = parser.addStringOption('g', "genome"); CmdLineParser.Option dataServerOption = parser.addStringOption('d', "dataServerURL"); CmdLineParser.Option genomeServerOption = parser.addStringOption('u', "genomeServerURL"); CmdLineParser.Option indexFileOption = parser.addStringOption('i', "indexFile"); CmdLineParser.Option coverageFileOption = parser.addStringOption('c', "coverageFile"); CmdLineParser.Option nameOption = parser.addStringOption('n', "name"); try { parser.parse(args); } catch (CmdLineParser.IllegalOptionValueException e) { e.printStackTrace(); // This is not logged because the logger is not initialized yet. } catch (CmdLineParser.UnknownOptionException e) { e.printStackTrace(); } propertyOverrides = (String) parser.getOptionValue(propertyFileOption); batchFile = (String) parser.getOptionValue(batchFileOption); port = (String) parser.getOptionValue(portOption); genomeId = (String) parser.getOptionValue(genomeOption); dataServerURL = (String) parser.getOptionValue(dataServerOption); genomeServerURL = (String) parser.getOptionValue(genomeServerOption); indexFile = (String) parser.getOptionValue(indexFileOption); coverageFile = (String) parser.getOptionValue(coverageFileOption); name = (String) parser.getOptionValue(nameOption); String[] nonOptionArgs = parser.getRemainingArgs(); if (nonOptionArgs != null && nonOptionArgs.length > 0) { String firstArg = nonOptionArgs[0]; if (firstArg != null && !firstArg.equals("ignore")) { log.info("Loading: " + firstArg); if (firstArg.endsWith(".xml") || firstArg.endsWith(".php") || firstArg.endsWith(".php3") || firstArg.endsWith(".session")) { sessionFile = firstArg; } else { dataFileString = firstArg; } } if (nonOptionArgs.length > 1) { locusString = nonOptionArgs[1]; } // Alternative implementation // String firstArg = StringUtils.decodeURL(nonOptionArgs[0]); // firstArg=checkEqualsAndExtractParamter(firstArg); // if (firstArg != null && !firstArg.equals("ignore")) { // log.info("Loading: " + firstArg); // if (firstArg.endsWith(".xml") || firstArg.endsWith(".php") || firstArg.endsWith(".php3") // || firstArg.endsWith(".session")) { // sessionFile = firstArg; // } else { // dataFileString = firstArg; // if (nonOptionArgs.length > 1) { // // check if arg contains = for all args // for (String arg: nonOptionArgs ) { // arg = checkEqualsAndExtractParamter(arg); // if (arg != null) locusString = arg; } } private String checkEqualsAndExtractParamter(String arg) { if (arg == null) return null; int eq = arg.indexOf("="); if (eq > 0) { // we got a key=value String key = arg.substring(0, eq); String val = arg.substring(eq + 1); if (key.equalsIgnoreCase("server")) { PreferenceManager.getInstance().put(PreferenceManager.IONTORRENT_SERVER, val); log.info("Got server: " + key + "=" + val); return null; } else if (key.equalsIgnoreCase("sessionURL") || key.equalsIgnoreCase("file")) { if (val.endsWith(".xml") || val.endsWith(".php") || val.endsWith(".php3") || val.endsWith(".session")) { log.info("Got session: " + key + "=" + val); sessionFile = val; } else { log.info("Got dataFileString: " + key + "=" + val); dataFileString = val; } return null; } else if (key.equalsIgnoreCase("locus") || key.equalsIgnoreCase("position")) { log.info("Got locus: " + key + "=" + val); locusString = val; return null; } else { log.info("Currently not handled: " + key + "=" + val); return null; } } return arg; } public String getBatchFile() { return batchFile; } public String getSessionFile() { return sessionFile; } public String getDataFileString() { return dataFileString; } public String getLocusString() { return locusString; } public String getPropertyOverrides() { return propertyOverrides; } public String getGenomeId() { return genomeId; } public String getPort() { return port; } public String getDataServerURL() { return dataServerURL; } public String getGenomeServerURL() { return genomeServerURL; } public String getIndexFile() { return indexFile; } public String getCoverageFile() { return coverageFile; } public String getName() { return name; } } }
package org.jgroups.util; import org.jgroups.*; import org.jgroups.TimeoutException; import org.jgroups.auth.AuthToken; import org.jgroups.blocks.Connection; import org.jgroups.conf.ClassConfigurator; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.logging.Log; import org.jgroups.protocols.*; import org.jgroups.protocols.pbcast.FLUSH; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.protocols.pbcast.STABLE; import org.jgroups.protocols.relay.SiteMaster; import org.jgroups.protocols.relay.SiteUUID; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.annotation.Annotation; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban */ public class Util { private static NumberFormat f; private static Map<Class<? extends Object>,Byte> PRIMITIVE_TYPES=new HashMap<Class<? extends Object>,Byte>(15); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; private static final byte TYPE_BYTEARRAY = 19; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; private static short COUNTER=1; private static Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN=Pattern.compile("[A-Z]+"); private static Pattern ATTR_NAME_TO_METHOD_NAME_PATTERN=Pattern.compile("_."); protected static int CCHM_INITIAL_CAPACITY=16; protected static float CCHM_LOAD_FACTOR=0.75f; protected static int CCHM_CONCURRENCY_LEVEL=16; /** The max size of an address list, e.g. used in View or Digest when toString() is called. Limiting this * reduces the amount of log data */ public static int MAX_LIST_PRINT_SIZE=20; public static final Class<?>[] getUnicastProtocols() { return new Class<?>[]{UNICAST.class, UNICAST2.class, UNICAST3.class}; } public static enum AddressScope {GLOBAL, SITE_LOCAL, LINK_LOCAL, LOOPBACK, NON_LOOPBACK}; private static StackType ip_stack_type=_getIpStackType(); protected static ResourceBundle resource_bundle; static { resource_bundle=ResourceBundle.getBundle("jg-messages",Locale.getDefault(),Util.class.getClassLoader()); try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns","false")); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); // f.setMinimumFractionDigits(2); f.setMaximumFractionDigits(2); PRIMITIVE_TYPES.put(Boolean.class, TYPE_BOOLEAN); PRIMITIVE_TYPES.put(Byte.class, TYPE_BYTE); PRIMITIVE_TYPES.put(Character.class, TYPE_CHAR); PRIMITIVE_TYPES.put(Double.class, TYPE_DOUBLE); PRIMITIVE_TYPES.put(Float.class, TYPE_FLOAT); PRIMITIVE_TYPES.put(Integer.class, TYPE_INT); PRIMITIVE_TYPES.put(Long.class, TYPE_LONG); PRIMITIVE_TYPES.put(Short.class, TYPE_SHORT); PRIMITIVE_TYPES.put(String.class, TYPE_STRING); PRIMITIVE_TYPES.put(byte[].class, TYPE_BYTEARRAY); if(ip_stack_type == StackType.Unknown) ip_stack_type=StackType.IPv6; try { String cchm_initial_capacity=System.getProperty(Global.CCHM_INITIAL_CAPACITY); if(cchm_initial_capacity != null) CCHM_INITIAL_CAPACITY=Integer.valueOf(cchm_initial_capacity); } catch(SecurityException ex) {} try { String cchm_load_factor=System.getProperty(Global.CCHM_LOAD_FACTOR); if(cchm_load_factor != null) CCHM_LOAD_FACTOR=Float.valueOf(cchm_load_factor); } catch(SecurityException ex) {} try { String cchm_concurrency_level=System.getProperty(Global.CCHM_CONCURRENCY_LEVEL); if(cchm_concurrency_level != null) CCHM_CONCURRENCY_LEVEL=Integer.valueOf(cchm_concurrency_level); } catch(SecurityException ex) {} try { String tmp=System.getProperty(Global.MAX_LIST_PRINT_SIZE); if(tmp != null) MAX_LIST_PRINT_SIZE=Integer.valueOf(tmp); } catch(SecurityException ex) { } } public static void assertTrue(boolean condition) { assert condition; } public static void assertTrue(String message, boolean condition) { if(message != null) assert condition : message; else assert condition; } public static void assertFalse(boolean condition) { assertFalse(null, condition); } public static void assertFalse(String message, boolean condition) { if(message != null) assert !condition : message; else assert !condition; } public static void assertEquals(String message, Object val1, Object val2) { if(message != null) { assert val1.equals(val2) : message; } else { assert val1.equals(val2); } } public static void assertEquals(Object val1, Object val2) { assertEquals(null, val1, val2); } public static void assertNotNull(String message, Object val) { if(message != null) assert val != null : message; else assert val != null; } public static void assertNotNull(Object val) { assertNotNull(null, val); } public static void assertNull(String message, Object val) { if(message != null) assert val == null : message; else assert val == null; } public static int getNextHigherPowerOfTwo(int num) { if (num <= 0) return 1; int highestBit = Integer.highestOneBit(num); return num <= highestBit ? highestBit : highestBit << 1; } public static String bold(String msg) { StringBuilder sb=new StringBuilder("\033[1m"); sb.append(msg).append("\033[0m"); return sb.toString(); } public static String getMessage(String key) { return key != null? resource_bundle.getString(key) : null; } /** * Returns a default stack for testing with transport = SHARED_LOOPBACK * @param additional_protocols Any number of protocols to add to the top of the returned protocol list * @return */ public static Protocol[] getTestStack(Protocol ... additional_protocols) { Protocol[] protocols={ new SHARED_LOOPBACK(), new PING().timeout(1000), new NAKACK2(), new UNICAST3(), new STABLE(), new GMS(), new FRAG2().fragSize(8000), }; if(additional_protocols == null) return protocols; Protocol[] tmp=Arrays.copyOf(protocols, protocols.length + additional_protocols.length); System.arraycopy(additional_protocols, 0, tmp, protocols.length, additional_protocols.length); return tmp; } /** * Blocks until all channels have the same view * @param timeout How long to wait (max in ms) * @param interval Check every interval ms * @param channels The channels which should form the view. The expected view size is channels.length. * Must be non-null */ public static void waitUntilAllChannelsHaveSameSize(long timeout, long interval, Channel... channels) throws TimeoutException { int size=channels.length; if(interval >= timeout || timeout <= 0) throw new IllegalArgumentException("interval needs to be smaller than timeout or timeout needs to be > 0"); long target_time=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() <= target_time) { boolean all_channels_have_correct_size=true; for(Channel ch: channels) { View view=ch.getView(); if(view == null || view.size() != size) { all_channels_have_correct_size=false; break; } } if(all_channels_have_correct_size) return; Util.sleep(interval); } View[] views=new View[channels.length]; StringBuilder sb=new StringBuilder(); for(int i=0; i < channels.length; i++) { views[i]=channels[i].getView(); sb.append(channels[i].getName()).append(": ").append(views[i]).append("\n"); } for(View view: views) if(view == null || view.size() != size) throw new TimeoutException("Timeout " + timeout + " kicked in, views are:\n" + sb); } /** * Waits until a list has the expected number of elements. Throws an exception if not met * @param list The list * @param expected_size The expected size * @param timeout The time to wait (in ms) * @param interval The interval at which to get the size of the list (in ms) * @param <T> The type of the list */ public static <T> void waitUntilListHasSize(List<T> list, int expected_size, long timeout, long interval) { if(list == null) throw new IllegalStateException("list is null"); long target_time=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < target_time) { if(list.size() == expected_size) break; Util.sleep(interval); } assert list.size() == expected_size : "list doesn't have the expected (" + expected_size + ") elements: " + list; } public static void addFlush(Channel ch, FLUSH flush) { if(ch == null || flush == null) throw new IllegalArgumentException("ch and flush have to be non-null"); ProtocolStack stack=ch.getProtocolStack(); stack.insertProtocolAtTop(flush); } public static void setScope(Message msg, short scope) { SCOPE.ScopeHeader hdr=SCOPE.ScopeHeader.createMessageHeader(scope); msg.putHeader(Global.SCOPE_ID, hdr); msg.setFlag(Message.Flag.SCOPED); } public static short getScope(Message msg) { SCOPE.ScopeHeader hdr=(SCOPE.ScopeHeader)msg.getHeader(Global.SCOPE_ID); return hdr != null? hdr.getScope() : 0; } public static byte[] createAuthenticationDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException { ByteArrayOutputStream baos = new ByteArrayOutputStream(128); DataOutputStream out = new DataOutputStream(baos); byte[] digest = createDigest(passcode, t1, q1); out.writeLong(t1); out.writeDouble(q1); out.writeInt(digest.length); out.write(digest); out.flush(); return baos.toByteArray(); } public static byte[] createDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(passcode.getBytes()); ByteBuffer bb = ByteBuffer.allocate(16); //8 bytes for long and double each bb.putLong(t1); bb.putDouble(q1); md.update(bb); return md.digest(); } /** * Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones * @param sock * @param dest * @param sock_conn_timeout * @throws IOException */ public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException { if(dest instanceof InetSocketAddress) { InetAddress addr=((InetSocketAddress)dest).getAddress(); if(addr instanceof Inet6Address) { Inet6Address tmp=(Inet6Address)addr; if(tmp.getScopeId() != 0) { dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()), ((InetSocketAddress)dest).getPort()); } } } sock.connect(dest, sock_conn_timeout); } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(ServerSocket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } public static void close(Channel ch) { if(ch != null) { try {ch.close();} catch(Throwable t) {} } } public static void close(Channel ... channels) { if(channels != null) { for(Channel ch: channels) Util.close(ch); } } public static void close(Connection conn) { if(conn != null) { try {conn.close();} catch(Throwable t) {} } } public static void close(Connection ... conns) { for(Connection conn: conns) close(conn); } /** Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from * the view until failure detection has kicked in and the new coord installed the new view */ public static void shutdown(Channel ch) throws Exception { DISCARD discard=new DISCARD(); discard.setLocalAddress(ch.getAddress()); discard.setDiscardAll(true); ProtocolStack stack=ch.getProtocolStack(); TP transport=stack.getTransport(); stack.insertProtocol(discard, ProtocolStack.ABOVE, transport.getClass()); //abruptly shutdown FD_SOCK just as in real life when member gets killed non gracefully FD_SOCK fd = (FD_SOCK) ch.getProtocolStack().findProtocol(FD_SOCK.class); if(fd != null) fd.stopServerSocket(false); View view=ch.getView(); if (view != null) { ViewId vid = view.getViewId(); List<Address> members = Arrays.asList(ch.getAddress()); ViewId new_vid = new ViewId(ch.getAddress(), vid.getId() + 1); View new_view = new View(new_vid, members); // inject view in which the shut down member is the only element GMS gms = (GMS) stack.findProtocol(GMS.class); gms.installView(new_view); } Util.close(ch); } public static byte setFlag(byte bits, byte flag) { return bits |= flag; } public static boolean isFlagSet(byte bits, byte flag) { return (bits & flag) == flag; } public static byte clearFlags(byte bits, byte flag) { return bits &= ~flag; } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; byte type=buffer[offset]; switch(type) { case TYPE_NULL: return null; case TYPE_STREAMABLE: ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); InputStream in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); in=new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela) try { retval=((ObjectInputStream)in).readObject(); } finally { Util.close(in); } break; case TYPE_BOOLEAN: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get() == 1; case TYPE_BYTE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get(); case TYPE_CHAR: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getChar(); case TYPE_DOUBLE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getDouble(); case TYPE_FLOAT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getFloat(); case TYPE_INT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getInt(); case TYPE_LONG: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getLong(); case TYPE_SHORT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getShort(); case TYPE_STRING: byte[] tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return new String(tmp); case TYPE_BYTEARRAY: tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return tmp; default: throw new IllegalArgumentException("type " + type + " is invalid"); } return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable or Streamable. */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(obj == null) return ByteBuffer.allocate(Global.BYTE_SIZE).put(TYPE_NULL).array(); if(obj instanceof Streamable) { final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); final ExposedDataOutputStream out=new ExposedDataOutputStream(out_stream); out_stream.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); return out_stream.toByteArray(); } Byte type=PRIMITIVE_TYPES.get(obj.getClass()); if(type == null) { // will throw an exception if object is not serializable final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); out_stream.write(TYPE_SERIALIZABLE); ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); return out_stream.toByteArray(); } switch(type) { case TYPE_BOOLEAN: return ByteBuffer.allocate(Global.BYTE_SIZE * 2).put(TYPE_BOOLEAN) .put((Boolean)obj? (byte)1 : (byte)0).array(); case TYPE_BYTE: return ByteBuffer.allocate(Global.BYTE_SIZE *2).put(TYPE_BYTE).put((Byte)obj).array(); case TYPE_CHAR: return ByteBuffer.allocate(Global.BYTE_SIZE *3).put(TYPE_CHAR).putChar((Character)obj).array(); case TYPE_DOUBLE: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.DOUBLE_SIZE).put(TYPE_DOUBLE) .putDouble((Double)obj).array(); case TYPE_FLOAT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.FLOAT_SIZE).put(TYPE_FLOAT) .putFloat((Float)obj).array(); case TYPE_INT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.INT_SIZE).put(TYPE_INT) .putInt((Integer)obj).array(); case TYPE_LONG: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.LONG_SIZE).put(TYPE_LONG) .putLong((Long)obj).array(); case TYPE_SHORT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.SHORT_SIZE).put(TYPE_SHORT) .putShort((Short)obj).array(); case TYPE_STRING: String str=(String)obj; byte[] buf=new byte[str.length()]; for(int i=0; i < buf.length; i++) buf[i]=(byte)str.charAt(i); return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_STRING).put(buf, 0, buf.length).array(); case TYPE_BYTEARRAY: buf=(byte[])obj; return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_BYTEARRAY) .put(buf, 0, buf.length).array(); default: throw new IllegalArgumentException("type " + type + " is invalid"); } } public static void objectToStream(Object obj, DataOutput out) throws Exception { if(obj == null) { out.write(TYPE_NULL); return; } Byte type; if(obj instanceof Streamable) { // use Streamable if we can out.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); } else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) { out.write(type.byteValue()); switch(type.byteValue()) { case TYPE_BOOLEAN: out.writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: out.writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: out.writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: out.writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: out.writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: out.writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: out.writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: out.writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { out.writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream((OutputStream)out); try { oos.writeObject(str); } finally { oos.close(); } } else { out.writeBoolean(false); out.writeUTF(str); } break; case TYPE_BYTEARRAY: byte[] buf=(byte[])obj; out.writeInt(buf.length); out.write(buf, 0, buf.length); break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out.write(TYPE_SERIALIZABLE); ObjectOutputStream tmp=new ObjectOutputStream((OutputStream)out); tmp.writeObject(obj); } } public static Object objectFromStream(DataInput in) throws Exception { if(in == null) return null; Object retval=null; byte b=in.readByte(); switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: retval=readGenericStreamable(in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable ObjectInputStream tmp=new ObjectInputStream((InputStream)in); retval=tmp.readObject(); break; case TYPE_BOOLEAN: retval=Boolean.valueOf(in.readBoolean()); break; case TYPE_BYTE: retval=Byte.valueOf(in.readByte()); break; case TYPE_CHAR: retval=Character.valueOf(in.readChar()); break; case TYPE_DOUBLE: retval=Double.valueOf(in.readDouble()); break; case TYPE_FLOAT: retval=Float.valueOf(in.readFloat()); break; case TYPE_INT: retval=Integer.valueOf(in.readInt()); break; case TYPE_LONG: retval=Long.valueOf(in.readLong()); break; case TYPE_SHORT: retval=Short.valueOf(in.readShort()); break; case TYPE_STRING: if(in.readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream((InputStream)in); try { retval=ois.readObject(); } finally { ois.close(); } } else { retval=in.readUTF(); } break; case TYPE_BYTEARRAY: int len=in.readInt(); byte[] tmpbuf=new byte[len]; in.readFully(tmpbuf, 0, tmpbuf.length); retval=tmpbuf; break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } public static Streamable streamableFromByteBuffer(Class<? extends Streamable> cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static <T extends Streamable> Streamable streamableFromByteBuffer(Class<T> cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) T retval=cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static <T extends Streamable> T streamableFromBuffer(Class<T> clazz, byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) return (T)Util.readStreamable(clazz,in); } public static <T extends Streamable> T streamableFromBuffer(Class<T> clazz, byte[] buffer) throws Exception { return streamableFromBuffer(clazz,buffer,0,buffer.length); } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); return result; } public static Buffer streamableToBuffer(Streamable obj) { final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); try { Util.writeStreamable(obj,out); return out_stream.getBuffer(); } catch(Exception ex) { return null; } } public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); return result; } public static void writeAuthToken(AuthToken token, DataOutput out) throws Exception{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInput in) throws Exception { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe) { return null; } } public static void writeView(View view, DataOutput out) throws Exception { if(view == null) { out.writeBoolean(false); return; } out.writeBoolean(true); out.writeBoolean(view instanceof MergeView); view.writeTo(out); } public static View readView(DataInput in) throws Exception { if(in.readBoolean() == false) return null; boolean isMergeView=in.readBoolean(); View view; if(isMergeView) view=new MergeView(); else view=new View(); view.readFrom(in); return view; } public static void writeViewId(ViewId vid, DataOutput out) throws Exception { if(vid == null) { out.writeBoolean(false); return; } out.writeBoolean(true); vid.writeTo(out); } public static ViewId readViewId(DataInput in) throws Exception { if(in.readBoolean() == false) return null; ViewId retval=new ViewId(); retval.readFrom(in); return retval; } public static void writeAddress(Address addr, DataOutput out) throws Exception { byte flags=0; boolean streamable_addr=true; if(addr == null) { flags=Util.setFlag(flags, Address.NULL); out.writeByte(flags); return; } if(addr instanceof UUID) { Class<? extends Address> clazz=addr.getClass(); if(clazz.equals(UUID.class)) flags=Util.setFlag(flags, Address.UUID_ADDR); else if(clazz.equals(SiteUUID.class)) flags=Util.setFlag(flags, Address.SITE_UUID); else if(clazz.equals(SiteMaster.class)) flags=Util.setFlag(flags,Address.SITE_MASTER); else streamable_addr=false; } else if(addr instanceof IpAddress) flags=Util.setFlag(flags, Address.IP_ADDR); else streamable_addr=false; out.writeByte(flags); if(streamable_addr) addr.writeTo(out); else writeOtherAddress(addr, out); } public static Address readAddress(DataInput in) throws Exception { byte flags=in.readByte(); if(Util.isFlagSet(flags, Address.NULL)) return null; Address addr; if(Util.isFlagSet(flags, Address.UUID_ADDR)) { addr=new UUID(); addr.readFrom(in); } else if(Util.isFlagSet(flags, Address.SITE_UUID)) { addr=new SiteUUID(); addr.readFrom(in); } else if(Util.isFlagSet(flags, Address.SITE_MASTER)) { addr=new SiteMaster(); addr.readFrom(in); } else if(Util.isFlagSet(flags, Address.IP_ADDR)) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // flags if(addr == null) return retval; if(addr instanceof UUID) { Class<? extends Address> clazz=addr.getClass(); if(clazz.equals(UUID.class) || clazz.equals(SiteUUID.class) || clazz.equals(SiteMaster.class)) return retval+addr.size(); } if(addr instanceof IpAddress) return retval+addr.size(); retval+=Global.SHORT_SIZE; // magic number retval+=addr.size(); return retval; } public static int size(View view) { int retval=Global.BYTE_SIZE; // presence if(view != null) retval+=view.serializedSize() + Global.BYTE_SIZE; // merge view or regular view return retval; } public static int size(ViewId vid) { int retval=Global.BYTE_SIZE; // presence if(vid != null) retval+=vid.serializedSize(); return retval; } public static int size(String s) { int retval=Global.BYTE_SIZE; if(s != null) retval+=s.length() +2; return retval; } public static int size(byte[] buf) { int retval=Global.BYTE_SIZE + Global.INT_SIZE; if(buf != null) retval+=buf.length; return retval; } private static Address readOtherAddress(DataInput in) throws Exception { short magic_number=in.readShort(); Class<?> cl=ClassConfigurator.get(magic_number); if(cl == null) throw new RuntimeException("class for magic number " + magic_number + " not found"); Address addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutput out) throws Exception { short magic_number=ClassConfigurator.getMagicNumber(addr.getClass()); // write the class info if(magic_number == -1) throw new RuntimeException("magic number " + magic_number + " not found"); out.writeShort(magic_number); addr.writeTo(out); } /** * Writes a list of Addresses. Can contain 65K addresses at most * * @param v A Collection<Address> * @param out * @throws Exception */ public static void writeAddresses(Collection<? extends Address> v, DataOutput out) throws Exception { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); for(Address addr: v) { Util.writeAddress(addr, out); } } public static void writeAddresses(final Address[] addrs, DataOutput out) throws Exception { if(addrs == null) { out.writeShort(-1); return; } out.writeShort(addrs.length); for(Address addr: addrs) Util.writeAddress(addr, out); } /** * * * @param in * @param cl The type of Collection, e.g. ArrayList.class * @return Collection of Address objects * @throws Exception */ public static Collection<? extends Address> readAddresses(DataInput in, Class cl) throws Exception { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } public static Address[] readAddresses(DataInput in) throws Exception { short length=in.readShort(); if(length < 0) return null; Address[] retval=new Address[length]; for(int i=0; i < length; i++) { Address addr=Util.readAddress(in); retval[i]=addr; } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection<? extends Address> addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static long size(Address[] addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null) for(Address addr: addrs) retval+=Util.size(addr); return retval; } public static void writeStreamable(Streamable obj, DataOutput out) throws Exception { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInput in) throws Exception { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutput out) throws Exception { short magic_number; String classname; if(obj == null) { out.write(0); return; } out.write(1); magic_number=ClassConfigurator.getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } public static Streamable readGenericStreamable(DataInput in) throws Exception { Streamable retval=null; int b=in.readByte(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if (clazz==null) throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } else { classname=in.readUTF(); clazz=ClassConfigurator.get(classname); } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeClass(Class<?> classObject, DataOutput out) throws Exception { short magic_number=ClassConfigurator.getMagicNumber(classObject); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); out.writeUTF(classObject.getName()); } else { out.writeBoolean(true); out.writeShort(magic_number); } } public static Class<?> readClass(DataInput in) throws Exception { Class<?> clazz; boolean use_magic_number = in.readBoolean(); if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if(clazz == null) throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } else { String classname=in.readUTF(); clazz=ClassConfigurator.get(classname); } return clazz; } public static void writeObject(Object obj, DataOutput out) throws Exception { if(obj instanceof Streamable) { out.writeInt(-1); writeGenericStreamable((Streamable)obj, out); } else { byte[] buf=objectToByteBuffer(obj); out.writeInt(buf.length); out.write(buf, 0, buf.length); } } public static Object readObject(DataInput in) throws Exception { int len=in.readInt(); if(len == -1) return readGenericStreamable(in); byte[] buf=new byte[len]; in.readFully(buf, 0, len); return objectFromByteBuffer(buf); } public static void writeString(String s, DataOutput out) throws Exception { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInput in) throws Exception { int b=in.readByte(); if(b == 1) return in.readUTF(); return null; } public static String readFile(String filename) throws FileNotFoundException { FileInputStream in=new FileInputStream(filename); return readContents(in); } public static String readContents(InputStream input) { StringBuilder sb=new StringBuilder(); int ch; while(true) { try { ch=input.read(); if(ch != -1) sb.append((char)ch); else break; } catch(IOException e) { break; } } return sb.toString(); } public static byte[] readFileContents(String filename) throws IOException { File file=new File(filename); if(!file.exists()) throw new FileNotFoundException(filename); long length=file.length(); byte contents[]=new byte[(int)length]; InputStream in=new BufferedInputStream(new FileInputStream(filename)); int bytes_read=0; for(;;) { int tmp=in.read(contents, bytes_read, (int)(length - bytes_read)); if(tmp == -1) break; bytes_read+=tmp; if(bytes_read == length) break; } return contents; } public static byte[] readFileContents(InputStream input) throws IOException { byte contents[]=new byte[10000], buf[]=new byte[1024]; InputStream in=new BufferedInputStream(input); int bytes_read=0; for(;;) { int tmp=in.read(buf, 0, buf.length); if(tmp == -1) break; System.arraycopy(buf, 0, contents, bytes_read, tmp); bytes_read+=tmp; } byte[] retval=new byte[bytes_read]; System.arraycopy(contents, 0, retval, 0, bytes_read); return retval; } public static String parseString(DataInput in) { StringBuilder sb=new StringBuilder(); int ch; // read white space while(true) { try { ch=in.readByte(); if(ch == -1) { return null; // eof } if(Character.isWhitespace(ch)) { if(ch == '\n') return null; } else { sb.append((char)ch); break; } } catch(EOFException eof) { return null; } catch(IOException e) { break; } } while(true) { try { ch=in.readByte(); if(ch == -1) break; if(Character.isWhitespace(ch)) break; else { sb.append((char)ch); } } catch(IOException e) { break; } } return sb.toString(); } public static String readStringFromStdin(String message) throws Exception { System.out.print(message); System.out.flush(); System.in.skip(System.in.available()); BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); return reader.readLine().trim(); } public static long readLongFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Long.parseLong(tmp); } public static double readDoubleFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Double.parseDouble(tmp); } public static int readIntFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Integer.parseInt(tmp); } public static void writeByteBuffer(byte[] buf, DataOutput out) throws Exception { writeByteBuffer(buf, 0, buf.length, out); } public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutput out) throws Exception { if(buf != null) { out.write(1); out.writeInt(length); out.write(buf, offset, length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInput in) throws Exception { int b=in.readByte(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.readFully(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws Exception { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws Exception */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws Exception { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static <T> boolean match(T obj1, T obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1.hashCode() == a2.hashCode()) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } public static boolean patternMatch(String pattern, String str) { Pattern pat=Pattern.compile(pattern); Matcher matcher=pat.matcher(str); return matcher.matches(); } public static void main(String[] args) { boolean result=patternMatch(args[0],args[1]); System.out.println(args[1] + " matches " + args[0] + ": " + result); } public static <T> boolean different(T one, T two) { return !match(one, two); } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } public static void sleep(long timeout, int nanos) { //the Thread.sleep method is not precise at all regarding nanos if (timeout > 0 || nanos > 900000) { try { Thread.sleep(timeout + (nanos / 1000000), (nanos % 1000000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { //this isn't a superb metronome either, but allows a granularity //with a reasonable precision in the order of 50ths of millisecond long initialTime = System.nanoTime() - 200; while (System.nanoTime() < initialTime + nanos); } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } public static int keyPress(String msg) { System.out.println(msg); try { int ret=System.in.read(); System.in.skip(System.in.available()); return ret; } catch(IOException e) { return 0; } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * range) % range) + 1; } /** Sleeps between floor and ceiling milliseconds, chosen randomly */ public static void sleepRandom(long floor, long ceiling) { if(ceiling - floor<= 0) { return; } long diff = ceiling - floor; long r=(int)((Math.random() * 100000) % diff) + floor; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); _printThreads(bean, ids, sb); long[] deadlocks=bean.findDeadlockedThreads(); if(deadlocks != null && deadlocks.length > 0) { sb.append("deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } deadlocks=bean.findMonitorDeadlockedThreads(); if(deadlocks != null && deadlocks.length > 0) { sb.append("monitor deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } return sb.toString(); } protected static void _printThreads(ThreadMXBean bean, long[] ids, StringBuilder sb) { ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Object o: values) { String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map<Short,Header> headers=new HashMap<Short,Header>(m.getHeaders()); for(Map.Entry<Short,Header> entry: headers.entrySet()) { short id=entry.getKey(); Header value=entry.getValue(); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=ClassConfigurator.getProtocol(id) + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=ClassConfigurator.getProtocol(id) + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; s+=" "; } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } public static String mapToString(Map<? extends Object,? extends Object> map) { if(map == null) return "null"; StringBuilder sb=new StringBuilder(); for(Map.Entry<? extends Object,? extends Object> entry: map.entrySet()) { Object key=entry.getKey(); Object val=entry.getValue(); sb.append(key).append("="); if(val == null) sb.append("null"); else sb.append(val); sb.append("\n"); } return sb.toString(); } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printTime(long time, TimeUnit unit) { long ns=TimeUnit.NANOSECONDS.convert(time, unit); long us=TimeUnit.MICROSECONDS.convert(time, unit); long ms=TimeUnit.MILLISECONDS.convert(time, unit); long secs=TimeUnit.SECONDS.convert(time, unit); if(secs > 0) return secs + "s"; if(ms > 0) return ms + "ms"; if(us > 0) return us + " us"; return ns + "ns"; } public static String format(double value) { return f.format(value); } public static long readBytesLong(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (long)(num * tuple.getVal2()); } public static int readBytesInteger(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (int)(num * tuple.getVal2()); } public static double readBytesDouble(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return num * tuple.getVal2(); } private static Tuple<String,Long> readBytes(String input) { input=input.trim().toLowerCase(); int index=-1; long factor=1; if((index=input.indexOf("k")) != -1) factor=1000; else if((index=input.indexOf("kb")) != -1) factor=1000; else if((index=input.indexOf("m")) != -1) factor=1000000; else if((index=input.indexOf("mb")) != -1) factor=1000000; else if((index=input.indexOf("g")) != -1) factor=1000000000; else if((index=input.indexOf("gb")) != -1) factor=1000000000; String str=index != -1? input.substring(0, index) : input; return new Tuple<String,Long>(str, factor); } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static List<String> split(String input, int separator) { List<String> retval=new ArrayList<String>(); if(input == null) return retval; int index=0, end; while(true) { index=input.indexOf(separator, index); if(index == -1) break; index++; end=input.indexOf(separator, index); if(end == -1) retval.add(input.substring(index)); else retval.add(input.substring(index, end)); } return retval; } /* public static String[] commands(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) { tmp[0]=separator; if(tmp.length > 1) { String[] retval=new String[tmp.length -1]; retval[0]=tmp[0] + tmp[1]; System.arraycopy(tmp, 2, retval, 1, tmp.length-2); return retval; } return tmp; } return tmp; }*/ public static String[] components(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) tmp[0]=separator; return tmp; } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static List<Range> computeFragOffsets(int offset, int length, int frag_size) { List<Range> retval=new ArrayList<Range>(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static List<Range> computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static byte[] encode(long num) { if(num == 0) return new byte[]{0}; byte bytes_needed=numberOfBytesRequiredForLong(num); byte[] buf=new byte[bytes_needed + 1]; buf[0]=bytes_needed; int index=1; for(int i=0; i < bytes_needed; i++) buf[index++]=getByteAt(num, i); return buf; } static protected byte getByteAt(long num, int index) { return (byte)((num >> (index * 8))); } public static long decode(byte[] buf) { if(buf[0] == 0) return 0; byte length=buf[0]; return makeLong(buf, 1, length); } public static void writeLong(long num, DataOutput out) throws Exception { byte[] buf=encode(num); out.write(buf, 0, buf.length); } public static long readLong(DataInput in) throws Exception { byte len=in.readByte(); if(len == 0) return 0; byte[] buf=new byte[len]; in.readFully(buf, 0, len); return makeLong(buf, 0, len); } public static short makeShort(byte[] buf, int offset) { byte c1=buf[offset], c2=buf[offset+1]; return (short)((c1 << 8) + (c2 << 0)); } static long makeLong(byte[] buf, int offset, int len) { long retval=0; for(int i=0; i < len; i++) { byte b=buf[offset + i]; retval |= ((long)b & 0xff) << (i * 8); } return retval; } /** * Encode the highest delivered and received seqnos. The assumption is that the latter is always >= the former, and * highest received is not much higher than highest delivered. * @param highest_delivered * @param highest_received * @return */ public static byte[] encodeLongSequence(long highest_delivered, long highest_received) { if(highest_received < highest_delivered) throw new IllegalArgumentException("highest_received (" + highest_received + ") has to be >= highest_delivered (" + highest_delivered + ")"); if(highest_delivered == 0 &&highest_received == 0) return new byte[]{0}; long delta=highest_received - highest_delivered; // encode highest_delivered followed by delta byte num_bytes_for_hd=numberOfBytesRequiredForLong(highest_delivered), num_bytes_for_delta=numberOfBytesRequiredForLong(delta); byte[] buf=new byte[num_bytes_for_hd + num_bytes_for_delta + 1]; buf[0]=encodeLength(num_bytes_for_hd, num_bytes_for_delta); int index=1; for(int i=0; i < num_bytes_for_hd; i++) buf[index++]=getByteAt(highest_delivered, i); for(int i=0; i < num_bytes_for_delta; i++) buf[index++]=getByteAt(delta, i); return buf; } private static byte numberOfBytesRequiredForLong(long number) { if(number >> 56 != 0) return 8; if(number >> 48 != 0) return 7; if(number >> 40 != 0) return 6; if(number >> 32 != 0) return 5; if(number >> 24 != 0) return 4; if(number >> 16 != 0) return 3; if(number >> 8 != 0) return 2; if(number != 0) return 1; return 1; } /** Returns true if all elements in the collection are the same */ public static <T> boolean allEqual(Collection<T> elements) { if(elements.isEmpty()) return false; Iterator<T> it=elements.iterator(); T first=it.next(); while(it.hasNext()) { T el=it.next(); if(!el.equals(first)) return false; } return true; } public static byte size(long number) { return (byte)(number == 0? 1 : numberOfBytesRequiredForLong(number) +1); } /** * Writes 2 longs, where the second long needs to be >= the first (we only write the delta !) * @param hd * @param hr * @return */ public static byte size(long hd, long hr) { if(hd == 0 && hr == 0) return 1; byte num_bytes_for_hd=numberOfBytesRequiredForLong(hd), num_bytes_for_delta=numberOfBytesRequiredForLong(hr - hd); return (byte)(num_bytes_for_hd + num_bytes_for_delta + 1); } public static long[] decodeLongSequence(byte[] buf) { if(buf[0] == 0) return new long[]{0,0}; byte[] lengths=decodeLength(buf[0]); long[] seqnos=new long[2]; seqnos[0]=makeLong(buf, 1, lengths[0]); seqnos[1]=makeLong(buf, 1 + lengths[0], lengths[1]) + seqnos[0]; return seqnos; } public static void writeLongSequence(long highest_delivered, long highest_received, DataOutput out) throws Exception { byte[] buf=encodeLongSequence(highest_delivered, highest_received); out.write(buf, 0, buf.length); } public static long[] readLongSequence(DataInput in) throws Exception { byte len=in.readByte(); if(len == 0) return new long[]{0,0}; byte[] lengths=decodeLength(len); long[] seqnos=new long[2]; byte[] buf=new byte[lengths[0] + lengths[1]]; in.readFully(buf, 0, buf.length); seqnos[0]=makeLong(buf, 0, lengths[0]); seqnos[1]=makeLong(buf, lengths[0], lengths[1]) + seqnos[0]; return seqnos; } /** * Encodes the number of bytes needed into a single byte. The first number is encoded in the first nibble (the * first 4 bits), the second number in the second nibble * @param len1 The number of bytes needed to store a long. Must be between 0 and 8 * @param len2 The number of bytes needed to store a long. Must be between 0 and 8 * @return The byte storing the 2 numbers len1 and len2 */ public static byte encodeLength(byte len1, byte len2) { byte retval=len2; retval |= (len1 << 4); return retval; } public static byte[] decodeLength(byte len) { byte[] retval={(byte)0,(byte)0}; retval[0]=(byte)((len & 0xff) >> 4); retval[1]=(byte)(len & ~0xf0); // 0xff is the first nibble set (11110000) // retval[1]=(byte)(len << 4); // retval[1]=(byte)((retval[1] & 0xff) >> 4); return retval; } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { return printListWithDelimiter(list, delimiter, MAX_LIST_PRINT_SIZE); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter, int limit) { boolean first=true; StringBuilder sb=new StringBuilder(); int count=0, size=list.size(); for(T el: list) { if(first) first=false; else sb.append(delimiter); sb.append(el); if(limit > 0 && ++count >= limit) { if(size > count) sb.append(" ..."); // .append(list.size()).append("..."); break; } } return sb.toString(); } public static <T> String printListWithDelimiter(T[] list, String delimiter, int limit) { boolean first=true; StringBuilder sb=new StringBuilder(); int count=0, size=list.length; for(T el: list) { if(first) first=false; else sb.append(delimiter); sb.append(el); if(limit > 0 && ++count >= limit) { if(size > count) sb.append(" ..."); // .append(list.length).append("..."); break; } } return sb.toString(); } public static <T> String printMapWithDelimiter(Map<T,T> map, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(delimiter); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { return Arrays.toString(array); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } public static List<Address> leftMembers(Collection<Address> old_list, Collection<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(old_list); retval.removeAll(new_list); return retval; } public static List<Address> newMembers(List<Address> old_list, List<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(new_list); retval.removeAll(old_list); return retval; } public static <T> List<T> newElements(List<T> old_list, List<T> new_list) { if(new_list == null) return new ArrayList<T>(); List<T> retval=new ArrayList<T>(new_list); if(old_list != null) retval.removeAll(old_list); return retval; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static List<Address> pickSubset(List<Address> members, double subset_percentage) { List<Address> ret=new ArrayList<Address>(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=new ArrayList<Address>(members); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.add(tmp_mbrs.get(index)); tmp_mbrs.remove(index); } return ret; } public static <T> boolean contains(T key, T[] list) { if(list == null) return false; for(T tmp: list) if(tmp == key || tmp.equals(key)) return true; return false; } public static boolean containsViewId(Collection<View> views, ViewId vid) { for(View view: views) { ViewId tmp=view.getViewId(); if(tmp.equals(vid)) return true; } return false; } public static boolean containsId(short id, short[] ids) { if(ids == null) return false; for(short tmp: ids) if(tmp == id) return true; return false; } public static List<View> detectDifferentViews(Map<Address,View> map) { final List<View> ret=new ArrayList<View>(); for(View view: map.values()) { if(view == null) continue; ViewId vid=view.getViewId(); if(!Util.containsViewId(ret, vid)) ret.add(view); } return ret; } /** * Determines the members which take part in a merge. The resulting list consists of all merge coordinators * plus members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator * is B, but the merge participants are B and A. * @param map * @return */ public static Collection<Address> determineMergeParticipants(Map<Address,View> map) { Set<Address> coords=new HashSet<Address>(); Set<Address> all_addrs=new HashSet<Address>(); if(map == null) return Collections.emptyList(); for(View view: map.values()) all_addrs.addAll(view.getMembers()); for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) coords.add(coord); } for(Address coord: coords) { View view=map.get(coord); Collection<Address> mbrs=view != null? view.getMembers() : null; if(mbrs != null) all_addrs.removeAll(mbrs); } coords.addAll(all_addrs); return coords; } /** * This is the same or a subset of {@link #determineMergeParticipants(java.util.Map)} and contains only members * which are currently sub-partition coordinators. * @param map * @return */ public static Collection<Address> determineMergeCoords(Map<Address,View> map) { Set<Address> retval=new HashSet<Address>(); if(map != null) { for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) retval.add(coord); } } return retval; } /** * Similar to {@link #determineMergeCoords(java.util.Map)} but only actual coordinators are counted: an actual * coord is when the sender of a view is the first member of that view * @param map * @return */ public static Collection<Address> determineActualMergeCoords(Map<Address,View> map) { Set<Address> retval=new HashSet<Address>(); if(map != null) { for(Map.Entry<Address,View> entry: map.entrySet()) { Address sender=entry.getKey(); List<Address> members=entry.getValue().getMembers(); Address actual_coord=members.isEmpty() ? null : members.get(0); if(sender.equals(actual_coord)) retval.add(sender); } } return retval; } /** * Returns the rank of a member in a given view * @param view The view * @param addr The address of a member * @return A value between 1 and view.size(). The first member has rank 1, the second 2 and so on. If the * member is not found, 0 is returned */ public static int getRank(View view, Address addr) { if(view == null || addr == null) return 0; List<Address> members=view.getMembers(); for(int i=0; i < members.size(); i++) { Address mbr=members.get(i); if(mbr.equals(addr)) return i+1; } return 0; } public static int getRank(Collection<Address> members, Address addr) { if(members == null || addr == null) return -1; int index=0; for(Iterator<Address> it=members.iterator(); it.hasNext();) { Address mbr=it.next(); if(mbr.equals(addr)) return index+1; index++; } return -1; } public static <T> T pickRandomElement(List<T> list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } public static <T> T pickRandomElement(T[] array) { if(array == null) return null; int size=array.length; int index=(int)((Math.random() * size * 10) % size); return array[index]; } /** * Returns the object next to element in list * @param list * @param obj * @param <T> * @return */ public static <T> T pickNext(List<T> list, T obj) { if(list == null || obj == null) return null; Object[] array=list.toArray(); for(int i=0; i < array.length; i++) { T tmp=(T)array[i]; if(tmp != null && tmp.equals(obj)) return (T)array[(i+1) % array.length]; } return null; } /** Returns the next min(N,list.size()) elements after obj */ public static <T> List<T> pickNext(List<T> list, T obj, int num) { List<T> retval=new ArrayList<T>(); if(list == null || list.size() < 2) return retval; int index=list.indexOf(obj); if(index != -1) { for(int i=1; i <= num && i < list.size(); i++) { T tmp=list.get((index +i) % list.size()); if(!retval.contains(tmp)) retval.add(tmp); } } return retval; } public static JChannel createChannel(Protocol... prots) throws Exception { JChannel ch=new JChannel(false); ProtocolStack stack=new ProtocolStack(); ch.setProtocolStack(stack); for(Protocol prot: prots) { stack.addProtocol(prot); prot.setProtocolStack(stack); } stack.init(); return ch; } public static Address createRandomAddress() { return createRandomAddress(generateLocalName()); } /** Returns an array of num random addresses, named A, B, C etc */ public static Address[] createRandomAddresses(int num) { return createRandomAddresses(num, false); } public static Address[] createRandomAddresses(int num, boolean use_numbers) { Address[] addresses=new Address[num]; int number=1; char c='A'; for(int i=0; i < addresses.length; i++) addresses[i]=Util.createRandomAddress(use_numbers? String.valueOf(number++) : String.valueOf(c++)); return addresses; } public static Address createRandomAddress(String name) { UUID retval=UUID.randomUUID(); UUID.add(retval, name); return retval; } public static Object[][] createTimer() { return new Object[][] { {new DefaultTimeScheduler(5)}, {new TimeScheduler2()}, {new TimeScheduler3()}, {new HashedTimingWheel(5)} }; } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static List<Address> determineLeftMembers(List<Address> old_mbrs, List<Address> new_mbrs) { List<Address> retval=new ArrayList<Address>(); if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { Address mbr=old_mbrs.get(i); if(!new_mbrs.contains(mbr)) retval.add(mbr); } return retval; } public static String printViews(Collection<View> views) { StringBuilder sb=new StringBuilder(); boolean first=true; for(View view: views) { if(first) first=false; else sb.append(", "); sb.append(view.getViewId()); } return sb.toString(); } public static <T> String print(Collection<T> objs) { StringBuilder sb=new StringBuilder(); boolean first=true; for(T obj: objs) { if(first) first=false; else sb.append(", "); sb.append(obj); } return sb.toString(); } public static String print(byte[] array, int n) { StringBuilder sb=new StringBuilder(); if(array != null) { for(int i=0; i < Math.min(n, array.length); i++) sb.append("'").append(array[i]).append("' "); } return sb.toString(); } public static <T> String print(Map<T,T> map) { StringBuilder sb=new StringBuilder(); boolean first=true; for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(", "); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String printPingData(List<PingData> rsps) { StringBuilder sb=new StringBuilder(); if(rsps != null) { int total=rsps.size(); int servers=0, clients=0, coords=0; for(PingData rsp: rsps) { if(rsp.isCoord()) coords++; if(rsp.isServer()) servers++; else clients++; } sb.append(total + " total (" + servers + " servers (" + coords + " coord), " + clients + " clients)"); } return sb.toString(); } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws Exception { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { try { ByteArrayOutputStream output=new ExposedByteArrayOutputStream(); DataOutputStream out=new ExposedDataOutputStream(output); inst.writeTo(out); out.flush(); byte[] data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static Field[] getAllDeclaredFields(final Class clazz) { return getAllDeclaredFieldsWithAnnotations(clazz); } public static Field[] getAllDeclaredFieldsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Field> list=new ArrayList<Field>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Field[] fields=curr.getDeclaredFields(); if(fields != null) { for(Field field: fields) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(field.isAnnotationPresent(annotation)) list.add(field); } } else list.add(field); } } } Field[] retval=new Field[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Method[] getAllDeclaredMethods(final Class clazz) { return getAllDeclaredMethodsWithAnnotations(clazz); } public static Method[] getAllDeclaredMethodsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Method> list=new ArrayList<Method>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Method[] methods=curr.getDeclaredMethods(); if(methods != null) { for(Method method: methods) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(method.isAnnotationPresent(annotation)) list.add(method); } } else list.add(method); } } } Method[] retval=new Method[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Field getField(final Class clazz, String field_name) { if(clazz == null || field_name == null) return null; Field field=null; for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { try { return curr.getDeclaredField(field_name); } catch(NoSuchFieldException e) { } } return field; } public static void setField(Field field, Object target, Object value) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { field.set(target, value); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not set field " + field, iae); } } public static Object getField(Field field, Object target) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { return field.get(target); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not get field " + field, iae); } } public static Field findField(Object target, List<String> possible_names) { if(target == null) return null; for(Class<?> clazz=target.getClass(); clazz != null; clazz=clazz.getSuperclass()) { for(String name: possible_names) { try { return clazz.getDeclaredField(name); } catch(Exception e) { } } } return null; } public static Method findMethod(Object target, List<String> possible_names, Class<?> ... parameter_types) { if(target == null) return null; for(Class<?> clazz=target.getClass(); clazz != null; clazz=clazz.getSuperclass()) { for(String name: possible_names) { try { return clazz.getDeclaredMethod(name, parameter_types); } catch(Exception e) { } } } return null; } public static <T> Set<Class<T>> findClassesAssignableFrom(String packageName, Class<T> assignableFrom) throws IOException, ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Set<Class<T>> classes = new HashSet<Class<T>>(); String path = packageName.replace('.', '/'); URL resource = loader.getResource(path); if (resource != null) { String filePath = resource.getFile(); if (filePath != null && new File(filePath).isDirectory()) { for (String file : new File(filePath).list()) { if (file.endsWith(".class")) { String name = packageName + '.' + file.substring(0, file.indexOf(".class")); Class<T> clazz =(Class<T>)Class.forName(name); if (assignableFrom.isAssignableFrom(clazz)) classes.add(clazz); } } } } return classes; } public static List<Class<?>> findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a) throws IOException, ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); recurse(classes, packageName, a); return classes; } private static void recurse(List<Class<?>> classes, String packageName, Class<? extends Annotation> a) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String path = packageName.replace('.', '/'); URL resource = loader.getResource(path); if (resource != null) { String filePath = resource.getFile(); if (filePath != null && new File(filePath).isDirectory()) { for (String file : new File(filePath).list()) { if (file.endsWith(".class")) { String name = packageName + '.' + file.substring(0, file.indexOf(".class")); Class<?> clazz = Class.forName(name); if (clazz.isAnnotationPresent(a)) classes.add(clazz); } else if (new File(filePath,file).isDirectory()) { recurse(classes, packageName + "." + file, a); } } } } } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } public static void verifyRejectionPolicy(String str) throws Exception{ if(!(str.equalsIgnoreCase("run") || str.equalsIgnoreCase("abort")|| str.equalsIgnoreCase("discard")|| str.equalsIgnoreCase("discardoldest"))) { throw new Exception("Unknown rejection policy " + str); } } public static RejectedExecutionHandler parseRejectionPolicy(String rejection_policy) { if(rejection_policy == null) throw new IllegalArgumentException("rejection policy is null"); if(rejection_policy.equalsIgnoreCase("abort")) return new ThreadPoolExecutor.AbortPolicy(); if(rejection_policy.equalsIgnoreCase("discard")) return new ThreadPoolExecutor.DiscardPolicy(); if(rejection_policy.equalsIgnoreCase("discardoldest")) return new ThreadPoolExecutor.DiscardOldestPolicy(); if(rejection_policy.equalsIgnoreCase("run")) return new ThreadPoolExecutor.CallerRunsPolicy(); if(rejection_policy.toLowerCase().startsWith(CustomRejectionPolicy.NAME)) return new CustomRejectionPolicy(rejection_policy); if(rejection_policy.toLowerCase().startsWith(ProgressCheckRejectionPolicy.NAME)) return new ProgressCheckRejectionPolicy(rejection_policy); throw new IllegalArgumentException("rejection policy \"" + rejection_policy + "\" not known"); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static int[] parseCommaDelimitedInts(String s) { StringTokenizer tok; List<Integer> v=new ArrayList<Integer>(); Integer l; int[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Integer(tok.nextToken()); v.add(l); } if(v.isEmpty()) return null; retval=new int[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=v.get(i).intValue(); return retval; } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; List<Long> v=new ArrayList<Long>(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.add(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=v.get(i).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static List<String> parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Returns a list of IpAddresses */ public static List<IpAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; IpAddress addr; Set<IpAddress> retval=new HashSet<IpAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i <= port + port_range;i++) { addr=new IpAddress(host, i); retval.add(addr); } } return new LinkedList<IpAddress>(retval); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of * InetSocketAddress */ public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; InetSocketAddress addr; Set<InetSocketAddress> retval=new HashSet<InetSocketAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i < port + port_range;i++) { addr=new InetSocketAddress(host, i); retval.add(addr); } } return new LinkedList<InetSocketAddress>(retval); } public static List<String> parseStringList(String l, String separator) { List<String> tmp=new LinkedList<String>(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } public static String parseString(ByteBuffer buf) { return parseString(buf, true); } public static String parseString(ByteBuffer buf, boolean discard_whitespace) { StringBuilder sb=new StringBuilder(); char ch; // read white space while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } if(buf.remaining() == 0) return null; while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { sb.append(ch); } else break; } // read white space if(discard_whitespace) { while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } } return sb.toString(); } public static int readNewLine(ByteBuffer buf) { char ch; int num=0; while(buf.remaining() > 0) { ch=(char)buf.get(); num++; if(ch == '\n') break; } return num; } /** * Reads and discards all characters from the input stream until a \r\n or EOF is encountered * @param in * @return */ public static int discardUntilNewLine(InputStream in) { int ch; int num=0; while(true) { try { ch=in.read(); if(ch == -1) break; num++; if(ch == '\n') break; } catch(IOException e) { break; } } return num; } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), or a carriage return * followed immediately by a linefeed. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached * * @exception IOException If an I/O error occurs */ public static String readLine(InputStream in) throws IOException { StringBuilder sb=new StringBuilder(35); int ch; while(true) { ch=in.read(); if(ch == -1) return null; if(ch == '\r') { ; } else { if(ch == '\n') break; else { sb.append((char)ch); } } } return sb.toString(); } public static void writeString(ByteBuffer buf, String s) { for(int i=0; i < s.length(); i++) buf.put((byte)s.charAt(i)); } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { if(hostname == null) return null; int index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) return hostname.substring(0, index); else return hostname; } public static boolean startFlush(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) { int attemptCount = 0; while (attemptCount < numberOfAttempts) { try { c.startFlush(flushParticipants, false); return true; } catch (Exception e) { Util.sleepRandom(randomSleepTimeoutFloor, randomSleepTimeoutCeiling); attemptCount++; } } return false; } public static boolean startFlush(Channel c, List<Address> flushParticipants) { return startFlush(c,flushParticipants,4,1000,5000); } public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) { int attemptCount = 0; while(attemptCount < numberOfAttempts){ try{ c.startFlush(false); return true; } catch(Exception e) { Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling); attemptCount++; } } return false; } public static boolean startFlush(Channel c) { return startFlush(c,4,1000,5000); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } public static String generateLocalName() { String retval=null; try { retval=shortName(InetAddress.getLocalHost().getHostName()); } catch(Throwable e) { } if(retval == null) { try { retval=shortName(InetAddress.getByName(null).getHostName()); } catch(Throwable e) { retval="localhost"; } } long counter=Util.random(Short.MAX_VALUE *2); return retval + "-" + counter; } public synchronized static short incrCounter() { short retval=COUNTER++; if(COUNTER >= Short.MAX_VALUE) COUNTER=1; return retval; } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) { return new ConcurrentHashMap<K,V>(initial_capacity, load_factor, concurrency_level); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity) { return new ConcurrentHashMap<K,V>(initial_capacity); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap() { return new ConcurrentHashMap<K,V>(CCHM_INITIAL_CAPACITY, CCHM_LOAD_FACTOR, CCHM_CONCURRENCY_LEVEL); } public static <K,V> Map<K,V> createHashMap() { return new HashMap<K,V>(CCHM_INITIAL_CAPACITY, CCHM_LOAD_FACTOR); } public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=factory.createServerSocket(service_name, start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Finds first available port starting at start_port and returns server * socket. Will not bind to port >end_port. Sets srv_port */ public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port) throws Exception { ServerSocket ret=null; int original_start_port=start_port; while(true) { try { if(bind_addr == null) ret=factory.createServerSocket(service_name, start_port); else { // changed (bela Sept 7 2007): we accept connections on all NICs ret=factory.createServerSocket(service_name, start_port, 50, bind_addr); } } catch(SocketException bind_ex) { if(start_port == end_port) throw new BindException("No available port to bind to in range [" + original_start_port + " .. " + end_port + "]"); if(bind_addr != null && !bind_addr.isLoopbackAddress()) { NetworkInterface nic=NetworkInterface.getByInetAddress(bind_addr); if(nic == null) throw new BindException("bind_addr " + bind_addr + " is not a valid interface: " + bind_ex); } start_port++; continue; } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return factory.createDatagramSocket(service_name); } else { while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port); } catch(BindException bind_ex) { // port already used port++; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port, addr); } catch(BindException bind_ex) { // port already used port++; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static MulticastSocket createMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) throws IOException { if(mcast_addr != null && !mcast_addr.isMulticastAddress()) throw new IllegalArgumentException("mcast_addr (" + mcast_addr + ") is not a valid multicast address"); SocketAddress saddr=new InetSocketAddress(mcast_addr, port); MulticastSocket retval=null; try { retval=factory.createMulticastSocket(service_name, saddr); } catch(IOException ex) { if(log != null && log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a"; sb.append("could not bind to " + mcast_addr + " (" + type + " address)"); sb.append("; make sure your mcast_addr is of the same type as the preferred IP stack (IPv4 or IPv6)"); sb.append(" by checking the value of the system properties java.net.preferIPv4Stack and java.net.preferIPv6Addresses."); sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " + "(see http: sb.append("\nException was: " + ex); log.warn(sb.toString()); } } if(retval == null) retval=factory.createMulticastSocket(service_name, port); return retval; } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { // determine the desired values for bind_addr_str and bind_interface_str boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr_str =Util.getProperty(new String[]{Global.BIND_ADDR}, props, "bind_addr", ignore_systemprops, null); String bind_interface_str =Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress bind_addr=null; NetworkInterface bind_intf=null; StackType ip_version=Util.getIpStackType(); // 1. if bind_addr_str specified, get bind_addr and check version if(bind_addr_str != null) { bind_addr=InetAddress.getByName(bind_addr_str); // check that bind_addr_host has correct IP version boolean hasCorrectVersion = ((bind_addr instanceof Inet4Address && ip_version == StackType.IPv4) || (bind_addr instanceof Inet6Address && ip_version == StackType.IPv6)) ; if (!hasCorrectVersion) throw new IllegalArgumentException("bind_addr " + bind_addr_str + " has incorrect IP version") ; } // 2. if bind_interface_str specified, get interface and check that it has correct version if(bind_interface_str != null) { bind_intf=NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_intf != null && bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else if (bind_intf != null) { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } // 5. if neither bind address nor bind interface is specified, get the first non-loopback // address on any interface else if (bind_addr == null) { bind_addr = getNonLoopbackAddress() ; } // if we reach here, if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, using a loopback address of the correct version is our only option boolean localhost = false; if (bind_addr == null) { bind_addr = getLocalhost(ip_version); localhost = true; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(!localhost && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } if(props != null) { props.remove("bind_addr"); props.remove("bind_interface"); } return bind_addr; } /** * Method used by PropertyConverters.BindInterface to check that a bind_address is * consistent with a specified interface * * Idea: * 1. We are passed a bind_addr, which may be null * 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception, * otherwise, return the original bind_addr * 3. If null, get first non-loopback address on bind_interface, using stack preference to * get the IP version. If no non-loopback address, then just return null (i.e. the * bind_interface did not influence the decision). * */ public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) throws UnknownHostException, SocketException { NetworkInterface bind_intf=null; if(bind_addr != null && bind_addr.isLoopbackAddress()) return bind_addr; // 1. if bind_interface_str is null, or empty, no constraint on bind_addr if (bind_interface_str == null || bind_interface_str.trim().isEmpty()) return bind_addr; // 2. get the preferred IP version for the JVM - it will be IPv4 or IPv6 StackType ip_version = getIpStackType(); // 3. if bind_interface_str specified, get interface and check that it has correct version bind_intf=Util.getByName(bind_interface_str); // NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { String bind_addr_str = bind_addr.getHostAddress(); throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(bind_addr != null && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } // if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, return the original value of null so the default will be applied return bind_addr; } /** Finds a network interface of sub-interface with the given name */ public static NetworkInterface getByName(String name) throws SocketException { if(name == null) return null; Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface intf=en.nextElement(); if(intf.getName().equals(name)) return intf; Enumeration<NetworkInterface> en2=intf.getSubInterfaces(); while(en2.hasMoreElements()) { NetworkInterface intf2=en2.nextElement(); if(intf2.getName().equals(name)) { return intf2; } } } return null; } public static boolean checkForLinux() { return checkForPresence("os.name", "linux"); } public static boolean checkForHp() { return checkForPresence("os.name", "hp"); } public static boolean checkForSolaris() { return checkForPresence("os.name", "sun"); } public static boolean checkForWindows() { return checkForPresence("os.name", "win"); } public static boolean checkForMac() { return checkForPresence("os.name", "mac"); } public static boolean checkForAndroid() { return contains("java.vm.vendor", "android"); } private static boolean checkForPresence(String key, String value) { try { String tmp=System.getProperty(key); return tmp != null && tmp.trim().toLowerCase().startsWith(value); } catch(Throwable t) { return false; } } private static boolean contains(String key, String value) { try { String tmp=System.getProperty(key); return tmp != null && tmp.trim().toLowerCase().contains(value.trim().toLowerCase()); } catch(Throwable t) { return false; } } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } /** IP related utilities */ public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException { if (ip_version == StackType.IPv4) return InetAddress.getByName("127.0.0.1") ; else return InetAddress.getByName("::1") ; } /** * Returns the first non-loopback address on any interface on the current host. */ public static InetAddress getNonLoopbackAddress() throws SocketException { return getAddress(AddressScope.NON_LOOPBACK); } /** * Returns the first address on any interface of the current host, which satisfies scope */ public static InetAddress getAddress(AddressScope scope) throws SocketException { InetAddress address=null ; Enumeration intfs=NetworkInterface.getNetworkInterfaces(); while(intfs.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)intfs.nextElement(); try { if(intf.isUp()) { address=getAddress(intf, scope) ; if(address != null) return address; } } catch (SocketException e) { } } return null ; } /** * Returns a valid interface address based on a pattern. Iterates over all interfaces that are up and * returns the first match, based on the address or interface name * @param pattern Can be "match-addr:<pattern></pattern>" or "match-interface:<pattern></pattern>". Example:<p/> * match-addr:192.168.* * @return InetAddress or null if not found */ public static InetAddress getAddressByPatternMatch(String pattern) throws Exception { if(pattern == null) return null; String real_pattern=null; byte type=0; // 1=match-interface, 2: match-addr, 3: match-host, if(pattern.startsWith(Global.MATCH_INTF)) { type=1; real_pattern=pattern.substring(Global.MATCH_INTF.length() +1); } else if(pattern.startsWith(Global.MATCH_ADDR)) { type=2; real_pattern=pattern.substring(Global.MATCH_ADDR.length() +1); } else if(pattern.startsWith(Global.MATCH_HOST)) { type=3; real_pattern=pattern.substring(Global.MATCH_HOST.length() +1); } if(real_pattern == null) throw new IllegalArgumentException("expected " + Global.MATCH_ADDR + ":<pattern>, " + Global.MATCH_HOST + ":<pattern> or " + Global.MATCH_INTF + ":<pattern>"); Pattern pat=Pattern.compile(real_pattern); Enumeration intfs=NetworkInterface.getNetworkInterfaces(); while(intfs.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)intfs.nextElement(); try { if(!intf.isUp()) continue; switch(type) { case 1: // match by interface name String interface_name=intf.getName(); Matcher matcher=pat.matcher(interface_name); if(matcher.matches()) return getAddress(intf, null); break; case 2: // match by host address case 3: // match by host name for(Enumeration<InetAddress> en=intf.getInetAddresses(); en.hasMoreElements();) { InetAddress addr=en.nextElement(); String name=type == 3? addr.getHostName() : addr.getHostAddress(); matcher=pat.matcher(name); if(matcher.matches()) return addr; } break; } } catch (SocketException e) { } } return null; } /** * Returns the first address on the given interface on the current host, which satisfies scope * * @param intf the interface to be checked */ public static InetAddress getAddress(NetworkInterface intf, AddressScope scope) { StackType ip_version=Util.getIpStackType(); for(Enumeration addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=(InetAddress)addresses.nextElement(); boolean match=scope == null; if(scope != null) { switch(scope) { case GLOBAL: match=!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && !addr.isSiteLocalAddress(); break; case SITE_LOCAL: match=addr.isSiteLocalAddress(); break; case LINK_LOCAL: match=addr.isLinkLocalAddress(); break; case LOOPBACK: match=addr.isLoopbackAddress(); break; case NON_LOOPBACK: match=!addr.isLoopbackAddress(); break; default: throw new IllegalArgumentException("scope " + scope + " is unknown"); } } if(match) { if((addr instanceof Inet4Address && ip_version == StackType.IPv4) || (addr instanceof Inet6Address && ip_version == StackType.IPv6)) return addr; } } return null ; } /** * A function to check if an interface supports an IP version (i.e has addresses * defined for that IP version). * * @param intf * @return */ public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws UnknownHostException { boolean supportsVersion = false ; if (intf != null) { // get all the InetAddresses defined on the interface Enumeration addresses = intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if we find an address of correct version if ((address instanceof Inet4Address && (ip_version == StackType.IPv4)) || (address instanceof Inet6Address && (ip_version == StackType.IPv6))) { supportsVersion = true ; break ; } } } else { throw new UnknownHostException("network interface " + intf + " not found") ; } return supportsVersion ; } public static StackType getIpStackType() { return ip_stack_type; } /** Returns true if the 2 addresses are of the same type (IPv4 or IPv6) */ public static boolean sameAddresses(InetAddress one, InetAddress two) { return one == null || two == null || (one instanceof Inet6Address && two instanceof Inet6Address) || (one instanceof Inet4Address && two instanceof Inet4Address); } /** * Tries to determine the type of IP stack from the available interfaces and their addresses and from the * system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses) * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown * if the type cannot be detected */ private static StackType _getIpStackType() { boolean isIPv4StackAvailable = isStackAvailable(true) ; boolean isIPv6StackAvailable = isStackAvailable(false) ; // if only IPv4 stack available if (isIPv4StackAvailable && !isIPv6StackAvailable) { return StackType.IPv4; } // if only IPv6 stack available else if (isIPv6StackAvailable && !isIPv4StackAvailable) { return StackType.IPv6; } // if dual stack else if (isIPv4StackAvailable && isIPv6StackAvailable) { // get the System property which records user preference for a stack on a dual stack machine if(Boolean.getBoolean(Global.IPv4)) // has preference over java.net.preferIPv6Addresses return StackType.IPv4; if(Boolean.getBoolean(Global.IPv6)) return StackType.IPv6; return StackType.IPv6; } return StackType.Unknown; } public static boolean isStackAvailable(boolean ipv4) { Collection<InetAddress> all_addrs=getAllAvailableAddresses(); for(InetAddress addr: all_addrs) if(ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address)) return true; return false; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } public static Collection<InetAddress> getAllAvailableAddresses() { Set<InetAddress> retval=new HashSet<InetAddress>(); Enumeration en; try { en=NetworkInterface.getNetworkInterfaces(); if(en == null) return retval; while(en.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)en.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while(addrs.hasMoreElements()) retval.add(addrs.nextElement()); } } catch(SocketException e) { e.printStackTrace(); } return retval; } public static void checkIfValidAddress(InetAddress bind_addr, String prot_name) throws Exception { if(bind_addr.isAnyLocalAddress() || bind_addr.isLoopbackAddress()) return; Collection<InetAddress> addrs=getAllAvailableAddresses(); for(InetAddress addr: addrs) { if(addr.equals(bind_addr)) return; } throw new BindException("[" + prot_name + "] " + bind_addr + " is not a valid address on any local network interface"); } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) return false; tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static boolean isCoordinator(JChannel ch) { return isCoordinator(ch.getView(), ch.getAddress()); } public static boolean isCoordinator(View view, Address local_addr) { if(view == null || local_addr == null) return false; List<Address> mbrs=view.getMembers(); return !(mbrs == null || mbrs.isEmpty()) && local_addr.equals(mbrs.iterator().next()); } public static Address getCoordinator(View view) { if(view == null) return null; List<Address> mbrs=view.getMembers(); return !mbrs.isEmpty()? mbrs.get(0) : null; } public static MBeanServer getMBeanServer() { ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers != null && !servers.isEmpty()) { // return 'jboss' server if available for (int i = 0; i < servers.size(); i++) { MBeanServer srv = (MBeanServer) servers.get(i); if ("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer) servers.get(0); } else { //if it all fails, create a default return MBeanServerFactory.createMBeanServer(); } } public static void registerChannel(JChannel channel, String name) { MBeanServer server=Util.getMBeanServer(); if(server != null) { try { JmxConfigurator.registerChannel(channel, server, (name != null? name : "jgroups"), channel.getClusterName(), true); } catch(Exception e) { e.printStackTrace(); } } } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Go through the input string and replace any occurance of ${p} with the * props.getProperty(p) value. If there is no such property p defined, then * the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such * property p, then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the * primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with * System.getProperty("path.separator"). * * @param string - * the string with possible ${} references * @param props - * the source for ${x} property ref values, null means use * System.getProperty() * @return the input string with all property references replaced if any. If * there are no valid references the input string will be returned. * @throws {@link java.security.AccessControlException} * when not authorised to retrieved system properties */ public static String replaceProperties(final String string, final Properties props) { /** File separator value */ final String FILE_SEPARATOR=File.separator; /** Path separator value */ final String PATH_SEPARATOR=File.pathSeparator; /** File separator alias */ final String FILE_SEPARATOR_ALIAS="/"; /** Path separator alias */ final String PATH_SEPARATOR_ALIAS=":"; // States used in property parsing final int NORMAL=0; final int SEEN_DOLLAR=1; final int IN_BRACKET=2; final char[] chars=string.toCharArray(); StringBuilder buffer=new StringBuilder(); boolean properties=false; int state=NORMAL; int start=0; for(int i=0;i < chars.length;++i) { char c=chars[i]; // Dollar sign outside brackets if(c == '$' && state != IN_BRACKET) state=SEEN_DOLLAR; // Open bracket immediatley after dollar else if(c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state=IN_BRACKET; start=i - 1; } // No open bracket after dollar else if(state == SEEN_DOLLAR) state=NORMAL; // Closed bracket after open bracket else if(c == '}' && state == IN_BRACKET) { // No content if(start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else // Collect the system property { String value=null; String key=string.substring(start + 2, i); // check for alias if(FILE_SEPARATOR_ALIAS.equals(key)) { value=FILE_SEPARATOR; } else if(PATH_SEPARATOR_ALIAS.equals(key)) { value=PATH_SEPARATOR; } else { // check from the properties if(props != null) value=props.getProperty(key); else value=System.getProperty(key); if(value == null) { // Check for a default value ${key:default} int colon=key.indexOf(':'); if(colon > 0) { String realKey=key.substring(0, colon); if(props != null) value=props.getProperty(realKey); else value=System.getProperty(realKey); if(value == null) { // Check for a composite key, "key1,key2" value=resolveCompositeKey(realKey, props); // Not a composite key either, use the specified default if(value == null) value=key.substring(colon + 1); } } else { // No default, check for a composite key, "key1,key2" value=resolveCompositeKey(key, props); } } } if(value != null) { properties=true; buffer.append(value); } } start=i + 1; state=NORMAL; } } // No properties if(properties == false) return string; // Collect the trailing characters if(start != chars.length) buffer.append(string.substring(start, chars.length)); // Done return buffer.toString(); } /** * Try to resolve a "key" from the provided properties by checking if it is * actually a "key1,key2", in which case try first "key1", then "key2". If * all fails, return null. * * It also accepts "key1," and ",key2". * * @param key * the key to resolve * @param props * the properties to use * @return the resolved key or null */ private static String resolveCompositeKey(String key, Properties props) { String value=null; // Look for the comma int comma=key.indexOf(','); if(comma > -1) { // If we have a first part, try resolve it if(comma > 0) { // Check the first part String key1=key.substring(0, comma); if(props != null) value=props.getProperty(key1); else value=System.getProperty(key1); } // Check the second part, if there is one and first lookup failed if(value == null && comma < key.length() - 1) { String key2=key.substring(comma + 1); if(props != null) value=props.getProperty(key2); else value=System.getProperty(key2); } } // Return whatever we've found or null return value; } // /** // * Replaces variables with values from system properties. If a system property is not found, the property is // * removed from the output string // * @param input // * @return // */ // public static String substituteVariables(String input) throws Exception { // Collection<Configurator.ProtocolConfiguration> configs=Configurator.parseConfigurations(input); // for(Configurator.ProtocolConfiguration config: configs) { // for(Iterator<Map.Entry<String,String>> it=config.getProperties().entrySet().iterator(); it.hasNext();) { // Map.Entry<String,String> entry=it.next(); // return null; /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } public static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); if(default_val != null && !default_val.isEmpty()) default_val=default_val.trim(); // retval=System.getProperty(var, default_val); retval=_getProperty(var, default_val); } else { var=s; // retval=System.getProperty(var); retval=_getProperty(var, null); } return retval; } /** * Parses a var which might be comma delimited, e.g. bla,foo:1000: if 'bla' is set, return its value. Else, * if 'foo' is set, return its value, else return "1000" * @param var * @param default_value * @return */ private static String _getProperty(String var, String default_value) { if(var == null) return null; List<String> list=parseCommaDelimitedStrings(var); if(list == null || list.isEmpty()) { list=new ArrayList<String>(1); list.add(var); } String retval=null; for(String prop: list) { try { retval=System.getProperty(prop); if(retval != null) return retval; } catch(Throwable e) { } } return default_value; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Converts a method name to an attribute name, e.g. getFooBar() --> foo_bar, isFlag --> flag. * @param methodName * @return */ public static String methodNameToAttributeName(final String methodName) { String name=methodName; if((methodName.startsWith("get") || methodName.startsWith("set")) && methodName.length() > 3) name=methodName.substring(3); else if(methodName.startsWith("is") && methodName.length() > 2) name=methodName.substring(2); // Pattern p=Pattern.compile("[A-Z]+"); Matcher m=METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(name); StringBuffer sb=new StringBuffer(); while(m.find()) { int start=m.start(), end=m.end(); String str=name.substring(start, end).toLowerCase(); if(str.length() > 1) { String tmp1=str.substring(0, str.length() -1); String tmp2=str.substring(str.length() -1); str=tmp1 + "_" + tmp2; } if(start == 0) { m.appendReplacement(sb, str); } else m.appendReplacement(sb, "_" + str); } m.appendTail(sb); return sb.length() > 0? sb.toString() : methodName; } /** * Converts a method name to a Java attribute name, e.g. getFooBar() --> fooBar, isFlag --> flag. * @param methodName * @return */ public static String methodNameToJavaAttributeName(final String methodName) { String name=methodName; if((methodName.startsWith("get") || methodName.startsWith("set")) && methodName.length() > 3) name=methodName.substring(3); else if(methodName.startsWith("is") && methodName.length() > 2) name=methodName.substring(2); if(Character.isUpperCase(name.charAt(0))) return name.substring(0, 1).toLowerCase() + name.substring(1); return name; } public static String attributeNameToMethodName(String attr_name) { if(attr_name.contains("_")) { // Pattern p=Pattern.compile("_."); Matcher m=ATTR_NAME_TO_METHOD_NAME_PATTERN.matcher(attr_name); StringBuffer sb=new StringBuffer(); while(m.find()) { m.appendReplacement(sb, attr_name.substring(m.end() - 1, m.end()).toUpperCase()); } m.appendTail(sb); char first=sb.charAt(0); if(Character.isLowerCase(first)) { sb.setCharAt(0, Character.toUpperCase(first)); } return sb.toString(); } else { if(Character.isLowerCase(attr_name.charAt(0))) { return attr_name.substring(0, 1).toUpperCase() + attr_name.substring(1); } else { return attr_name; } } } public static String attributeNameToJavaMethodName(String attr_name) { String retval=attributeNameToMethodName(attr_name); if(Character.isUpperCase(retval.charAt(0))) return retval.substring(0, 1).toLowerCase() + retval.substring(1); return retval; } /** * Runs a task on a separate thread * @param task * @param factory * @param group * @param thread_name */ public static void runAsync(Runnable task, ThreadFactory factory, String thread_name) { Thread thread=factory.newThread(task, thread_name); thread.start(); } }
/** * A parsed statement. * Can be one of several types. An assignment statement, a conditional * statement, a block of statements making a procedure or just a plain command. */ import java.util.Vector; import java.util.Hashtable; public class Statement { /* * Possible types of statements. */ public static final int ASSIGN = 1; public static final int CONDITIONAL = 2; public static final int LOOP = 3; public static final int BLOCK = 4; public static final int COLOR = 10; public static final int LINEWIDTH = 11; public static final int MOVE = 12; public static final int DRAW = 13; public static final int CLEAR = 14; public static final int SLICEPATH = 15; public static final int STRIPEPATH = 16; public static final int STROKE = 17; public static final int FILL = 18; public static final int SCALE = 19; public static final int ROTATE = 20; public static final int NEWPAGE = 21; public static final int PRINT = 22; /* * Statement type for call to user defined procedure block. */ public static final int CALL = 100; private int mType; /* * Statements in an if-then-else statement. */ private Vector mThenStatements; private Vector mElseStatements; /* * Statements in a while loop statement. */ private Vector mLoopStatements; /* * Name of procedure block, * variable names of parameters to this procedure * and block of statements in a procedure in order of execution */ private String mBlockName; private Vector mStatementBlock; private Vector mParameters; /* * Name of variable in assignment. */ private String mAssignedVariable; private Expression []mExpressions; /* * Filename and line number within file that this * statement was read from. */ private String mFilename; private int mLineNumber; /* * Static statement type lookup table for fast lookup. */ private static Hashtable mStatementTypeLookup; static { mStatementTypeLookup = new Hashtable(); mStatementTypeLookup.put("color", new Integer(COLOR)); mStatementTypeLookup.put("colour", new Integer(COLOR)); mStatementTypeLookup.put("linewidth", new Integer(LINEWIDTH)); mStatementTypeLookup.put("move", new Integer(MOVE)); mStatementTypeLookup.put("draw", new Integer(DRAW)); mStatementTypeLookup.put("clear", new Integer(CLEAR)); mStatementTypeLookup.put("slicepath", new Integer(SLICEPATH)); mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH)); mStatementTypeLookup.put("stroke", new Integer(STROKE)); mStatementTypeLookup.put("fill", new Integer(FILL)); mStatementTypeLookup.put("scale", new Integer(SCALE)); mStatementTypeLookup.put("rotate", new Integer(ROTATE)); mStatementTypeLookup.put("newpage", new Integer(NEWPAGE)); mStatementTypeLookup.put("print", new Integer(PRINT)); } /** * Looks up identifier for a statement name. * @param s is the name of the statement. * @returns numeric code for this statement, or -1 if statement * is unknown. */ private int getStatementType(String s) { int retval; Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase()); if (type == null) retval = CALL; else retval = type.intValue(); return(retval); } /** * Creates a plain statement, either a built-in command or * a call to a procedure block that the user has defined. * @param keyword is the name statement. * @param expressions are the arguments for this statement. */ public Statement(String keyword, Expression []expressions) { mType = getStatementType(keyword); if (mType == CALL) mBlockName = keyword; mExpressions = expressions; } /** * Create an assignment statement. * @param variableName is the name of the variable being assigned. * @param value is the value being assigned to this variable. */ public Statement(String variableName, Expression value) { mType = ASSIGN; mAssignedVariable = variableName; mExpressions = new Expression[1]; mExpressions[0] = value; } /** * Creates a procedure, a block of statements to be executed together. * @param blockName is name of procedure block. * @param parameters variable names of parameters to this procedure. * @param statements list of statements that make up this procedure block. */ public Statement(String blockName, Vector parameters, Vector statements) { mBlockName = blockName; mParameters = parameters; mStatementBlock = statements; mType = BLOCK; } /** * Create an if, then, else, endif block of statements. * @param test is expression to test. * @param thenStatements is statements to execute if expression is true. * @param elseStatements is statements to execute if expression is false, * or null if there is no statement to execute. */ public Statement(Expression test, Vector thenStatements, Vector elseStatements) { mType = CONDITIONAL; mExpressions = new Expression[1]; mExpressions[0] = test; mThenStatements = thenStatements; mElseStatements = elseStatements; } /** * Create a while loop block of statements. * @param test is expression to test before each iteration of loop. * @param loopStatements is statements to execute for each loop iteration. */ public Statement(Expression test, Vector loopStatements) { mType = LOOP; mExpressions = new Expression[1]; mExpressions[0] = test; mLoopStatements = loopStatements; } /** * Sets the filename and line number that this statement was read from. * This is for use in any error message for this statement. * @param filename is name of file this statement was read from. * @param lineNumber is line number within file containing this statement. */ public void setFilenameAndLineNumber(String filename, int lineNumber) { mFilename = filename; mLineNumber = lineNumber; } /** * Returns filename and line number that this statement was read from. * @return string containing filename and line number. */ public String getFilenameAndLineNumber() { return(mFilename + " line " + mLineNumber); } /** * Returns the type of this statement. * @return statement type. */ public int getType() { return(mType); } public Expression []getExpressions() { return(mExpressions); } public String getAssignedVariable() { return(mAssignedVariable); } /** * Returns list of statements in "then" section of "if" statement. * @return list of statements. */ public Vector getThenStatements() { return(mThenStatements); } /** * Returns list of statements in "else" section of "if" statement. * @return list of statements. */ public Vector getElseStatements() { return(mElseStatements); } /** * Returns list of statements in while loop statement. * @return list of statements. */ public Vector getLoopStatements() { return(mLoopStatements); } /** * Return name of procedure block. * @return name of procedure. */ public String getBlockName() { return(mBlockName); } /** * Return variable names of parameters to a procedure. * @return list of parameter names. */ public Vector getBlockParameters() { return(mParameters); } /** * Return statements in a procedure. * @return vector of statements that make up the procedure. */ public Vector getStatementBlock() { return(mStatementBlock); } }
package mil.nga.sf.wkb.test; import java.io.IOException; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import org.junit.Test; import junit.framework.TestCase; import mil.nga.sf.CompoundCurve; import mil.nga.sf.Curve; import mil.nga.sf.Geometry; import mil.nga.sf.GeometryCollection; import mil.nga.sf.GeometryEnvelope; import mil.nga.sf.GeometryType; import mil.nga.sf.LineString; import mil.nga.sf.MultiLineString; import mil.nga.sf.MultiPoint; import mil.nga.sf.MultiPolygon; import mil.nga.sf.Point; import mil.nga.sf.Polygon; import mil.nga.sf.Surface; import mil.nga.sf.extended.ExtendedGeometryCollection; import mil.nga.sf.util.ByteReader; import mil.nga.sf.util.ByteWriter; import mil.nga.sf.util.GeometryEnvelopeBuilder; import mil.nga.sf.util.filter.FiniteFilterType; import mil.nga.sf.util.filter.PointFiniteFilter; import mil.nga.sf.wkb.GeometryCodes; import mil.nga.sf.wkb.GeometryReader; import mil.nga.sf.wkb.GeometryWriter; /** * Test Well Known Binary Geometries * * @author osbornb */ public class WKBTest { /** * Number of random geometries to create for each test */ private static final int GEOMETRIES_PER_TEST = 10; /** * Constructor */ public WKBTest() { } @Test public void testPoint() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a point Point point = WKBTestUtils.createPoint(WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(point); } } @Test public void testLineString() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a line string LineString lineString = WKBTestUtils.createLineString( WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(lineString); } } @Test public void testPolygon() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a polygon Polygon polygon = WKBTestUtils.createPolygon( WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(polygon); } } @Test public void testMultiPoint() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a multi point MultiPoint multiPoint = WKBTestUtils.createMultiPoint( WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(multiPoint); } } @Test public void testMultiLineString() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a multi line string MultiLineString multiLineString = WKBTestUtils .createMultiLineString(WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(multiLineString); } } @Test public void testMultiCurveWithLineStrings() throws IOException { // Test a pre-created WKB saved as the abstract MultiCurve type with // LineStrings byte[] bytes = new byte[] { 0, 0, 0, 0, 11, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 3, 64, 50, -29, -55, -6, 126, -15, 120, -64, 65, -124, -86, -46, -62, -60, 94, -64, 66, -31, -40, 124, -2, -47, -5, -64, 82, -13, -22, 8, -38, 6, 111, 64, 81, 58, 88, 78, -15, 82, 111, -64, 86, 20, -18, -37, 3, -99, -86, 0, 0, 0, 0, 2, 0, 0, 0, 10, 64, 98, 48, -84, 37, -62, 34, 98, -64, 68, -12, -81, 104, 13, -109, 6, -64, 101, -82, 76, -68, 34, 117, -110, 64, 39, -125, 83, 1, 50, 86, 8, -64, 83, 127, -93, 42, -89, 54, -56, -64, 67, -58, -13, -104, 1, -17, -10, 64, 97, 18, -82, -112, 100, -128, 16, 64, 68, -13, -86, -112, 112, 59, -3, 64, 67, -4, -71, -91, -16, -15, 85, -64, 49, 110, -16, 94, -71, 24, -13, -64, 94, 84, 94, -4, -78, -101, -75, -64, 80, 74, -39, 90, 38, 107, 104, 64, 72, -16, -43, 82, -112, -39, 77, 64, 28, 30, 97, -26, 64, 102, -110, 64, 92, 63, -14, -103, 99, -67, 63, -64, 65, -48, 84, -37, -111, -55, -25, -64, 101, -10, -62, -115, 104, -125, 28, -64, 66, 5, 108, -56, -59, 69, -36, -64, 83, 33, -36, -86, 106, -84, -16, 64, 70, 30, -104, -50, -57, 15, -7 }; TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE), bytes[4]); Geometry geometry = WKBTestUtils.readGeometry(bytes); TestCase.assertTrue(geometry instanceof GeometryCollection); TestCase.assertEquals(geometry.getGeometryType(), GeometryType.GEOMETRYCOLLECTION); @SuppressWarnings("unchecked") GeometryCollection<Curve> multiCurve = (GeometryCollection<Curve>) geometry; TestCase.assertEquals(2, multiCurve.numGeometries()); Geometry geometry1 = multiCurve.getGeometries().get(0); Geometry geometry2 = multiCurve.getGeometries().get(1); TestCase.assertTrue(geometry1 instanceof LineString); TestCase.assertTrue(geometry2 instanceof LineString); LineString lineString1 = (LineString) geometry1; LineString lineString2 = (LineString) geometry2; TestCase.assertEquals(3, lineString1.numPoints()); TestCase.assertEquals(10, lineString2.numPoints()); Point point1 = lineString1.startPoint(); Point point2 = lineString2.endPoint(); TestCase.assertEquals(18.889800697319032, point1.getX()); TestCase.assertEquals(-35.036463112927535, point1.getY()); TestCase.assertEquals(-76.52909336488278, point2.getX()); TestCase.assertEquals(44.2390383216843, point2.getY()); ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>( multiCurve); TestCase.assertEquals(GeometryType.MULTICURVE, extendedMultiCurve.getGeometryType()); geometryTester(extendedMultiCurve, multiCurve); byte[] bytes2 = WKBTestUtils.writeBytes(extendedMultiCurve); TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE), bytes2[4]); WKBTestUtils.compareByteArrays(bytes, bytes2); } @Test public void testMultiCurveWithCompoundCurve() throws IOException { // Test a pre-created WKB saved as the abstract MultiCurve type with a // CompoundCurve byte[] bytes = new byte[] { 0, 0, 0, 0, 11, 0, 0, 0, 1, 0, 0, 0, 0, 9, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 3, 65, 74, 85, 13, 0, -60, -101, -90, 65, 84, -23, 84, 60, -35, 47, 27, 65, 74, 85, 12, -28, -68, 106, 127, 65, 84, -23, 84, 123, 83, -9, -49, 65, 74, 85, 8, -1, 92, 40, -10, 65, 84, -23, 83, -81, -99, -78, 45, 0, 0, 0, 0, 2, 0, 0, 0, 2, 65, 74, 85, 8, -1, 92, 40, -10, 65, 84, -23, 83, -81, -99, -78, 45, 65, 74, 85, 13, 0, -60, -101, -90, 65, 84, -23, 84, 60, -35, 47, 27 }; TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE), bytes[4]); Geometry geometry = WKBTestUtils.readGeometry(bytes); TestCase.assertTrue(geometry instanceof GeometryCollection); TestCase.assertEquals(geometry.getGeometryType(), GeometryType.GEOMETRYCOLLECTION); @SuppressWarnings("unchecked") GeometryCollection<Curve> multiCurve = (GeometryCollection<Curve>) geometry; TestCase.assertEquals(1, multiCurve.numGeometries()); Geometry geometry1 = multiCurve.getGeometries().get(0); TestCase.assertTrue(geometry1 instanceof CompoundCurve); CompoundCurve compoundCurve1 = (CompoundCurve) geometry1; TestCase.assertEquals(2, compoundCurve1.numLineStrings()); LineString lineString1 = compoundCurve1.getLineStrings().get(0); LineString lineString2 = compoundCurve1.getLineStrings().get(1); TestCase.assertEquals(3, lineString1.numPoints()); TestCase.assertEquals(2, lineString2.numPoints()); TestCase.assertEquals(new Point(3451418.006, 5481808.951), lineString1.getPoint(0)); TestCase.assertEquals(new Point(3451417.787, 5481809.927), lineString1.getPoint(1)); TestCase.assertEquals(new Point(3451409.995, 5481806.744), lineString1.getPoint(2)); TestCase.assertEquals(new Point(3451409.995, 5481806.744), lineString2.getPoint(0)); TestCase.assertEquals(new Point(3451418.006, 5481808.951), lineString2.getPoint(1)); ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>( multiCurve); TestCase.assertEquals(GeometryType.MULTICURVE, extendedMultiCurve.getGeometryType()); geometryTester(extendedMultiCurve, multiCurve); byte[] bytes2 = WKBTestUtils.writeBytes(extendedMultiCurve); TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE), bytes2[4]); WKBTestUtils.compareByteArrays(bytes, bytes2); } @Test public void testMultiCurve() throws IOException { // Test the abstract MultiCurve type GeometryCollection<Curve> multiCurve = WKBTestUtils.createMultiCurve(); byte[] bytes = WKBTestUtils.writeBytes(multiCurve); ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>( multiCurve); TestCase.assertEquals(GeometryType.MULTICURVE, extendedMultiCurve.getGeometryType()); byte[] extendedBytes = WKBTestUtils.writeBytes(extendedMultiCurve); ByteReader byteReader = new ByteReader( java.util.Arrays.copyOfRange(bytes, 1, 5)); int code = byteReader.readInt(); byteReader.close(); byteReader = new ByteReader( java.util.Arrays.copyOfRange(extendedBytes, 1, 5)); int extendedCode = byteReader.readInt(); byteReader.close(); TestCase.assertEquals(GeometryCodes.getCode(multiCurve), code); TestCase.assertEquals( GeometryCodes.getCode(GeometryType.MULTICURVE, extendedMultiCurve.hasZ(), extendedMultiCurve.hasM()), extendedCode); Geometry geometry1 = WKBTestUtils.readGeometry(bytes); Geometry geometry2 = WKBTestUtils.readGeometry(extendedBytes); TestCase.assertTrue(geometry1 instanceof GeometryCollection); TestCase.assertTrue(geometry2 instanceof GeometryCollection); TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION, geometry1.getGeometryType()); TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION, geometry2.getGeometryType()); TestCase.assertEquals(multiCurve, geometry1); TestCase.assertEquals(geometry1, geometry2); @SuppressWarnings("unchecked") GeometryCollection<Geometry> geometryCollection1 = (GeometryCollection<Geometry>) geometry1; @SuppressWarnings("unchecked") GeometryCollection<Geometry> geometryCollection2 = (GeometryCollection<Geometry>) geometry2; TestCase.assertTrue(geometryCollection1.isMultiCurve()); TestCase.assertTrue(geometryCollection2.isMultiCurve()); geometryTester(multiCurve); geometryTester(extendedMultiCurve, multiCurve); } @Test public void testMultiSurface() throws IOException { // Test the abstract MultiSurface type GeometryCollection<Surface> multiSurface = WKBTestUtils .createMultiSurface(); byte[] bytes = WKBTestUtils.writeBytes(multiSurface); ExtendedGeometryCollection<Surface> extendedMultiSurface = new ExtendedGeometryCollection<>( multiSurface); TestCase.assertEquals(GeometryType.MULTISURFACE, extendedMultiSurface.getGeometryType()); byte[] extendedBytes = WKBTestUtils.writeBytes(extendedMultiSurface); ByteReader byteReader = new ByteReader( java.util.Arrays.copyOfRange(bytes, 1, 5)); int code = byteReader.readInt(); byteReader.close(); byteReader = new ByteReader( java.util.Arrays.copyOfRange(extendedBytes, 1, 5)); int extendedCode = byteReader.readInt(); byteReader.close(); TestCase.assertEquals(GeometryCodes.getCode(multiSurface), code); TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTISURFACE, extendedMultiSurface.hasZ(), extendedMultiSurface.hasM()), extendedCode); Geometry geometry1 = WKBTestUtils.readGeometry(bytes); Geometry geometry2 = WKBTestUtils.readGeometry(extendedBytes); TestCase.assertTrue(geometry1 instanceof GeometryCollection); TestCase.assertTrue(geometry2 instanceof GeometryCollection); TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION, geometry1.getGeometryType()); TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION, geometry2.getGeometryType()); TestCase.assertEquals(multiSurface, geometry1); TestCase.assertEquals(geometry1, geometry2); @SuppressWarnings("unchecked") GeometryCollection<Geometry> geometryCollection1 = (GeometryCollection<Geometry>) geometry1; @SuppressWarnings("unchecked") GeometryCollection<Geometry> geometryCollection2 = (GeometryCollection<Geometry>) geometry2; TestCase.assertTrue(geometryCollection1.isMultiSurface()); TestCase.assertTrue(geometryCollection2.isMultiSurface()); geometryTester(multiSurface); geometryTester(extendedMultiSurface, multiSurface); } @Test public void testMultiPolygon() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a multi polygon MultiPolygon multiPolygon = WKBTestUtils.createMultiPolygon( WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(multiPolygon); } } @Test public void testGeometryCollection() throws IOException { for (int i = 0; i < GEOMETRIES_PER_TEST; i++) { // Create and test a geometry collection GeometryCollection<Geometry> geometryCollection = WKBTestUtils .createGeometryCollection(WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip()); geometryTester(geometryCollection); } } @Test public void testMultiPolygon25() throws IOException { // Test a pre-created WKB hex saved as a 2.5D MultiPolygon byte[] bytes = hexStringToByteArray( "0106000080010000000103000080010000000F0000007835454789C456C0DFDB63124D3F2C4000000000000000004CE4512E89C456C060BF20D13F3F2C400000000000000000A42EC6388CC456C0E0A50400423F2C400000000000000000B4E3B1608CC456C060034E67433F2C400000000000000000F82138508DC456C09FD015C5473F2C400000000000000000ECD6591B8CC456C000C305BC5B3F2C4000000000000000001002AD0F8CC456C060DB367D5C3F2C40000000000000000010996DEF8AC456C0BF01756A6C3F2C4000000000000000007054A08B8AC456C0806A0C1F733F2C4000000000000000009422D81D8AC456C041CA3C5B8A3F2C4000000000000000003CCB05C489C456C03FC4FC52AA3F2C400000000000000000740315A689C456C0BFC8635EB33F2C400000000000000000E4A5630B89C456C0DFE726D6B33F2C400000000000000000F45A4F3389C456C000B07950703F2C4000000000000000007835454789C456C0DFDB63124D3F2C400000000000000000"); TestCase.assertEquals(1, bytes[0]); // little endian TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTIPOLYGON), bytes[1]); TestCase.assertEquals(0, bytes[2]); TestCase.assertEquals(0, bytes[3]); TestCase.assertEquals(-128, bytes[4]); Geometry geometry = WKBTestUtils.readGeometry(bytes); TestCase.assertTrue(geometry instanceof MultiPolygon); TestCase.assertEquals(geometry.getGeometryType(), GeometryType.MULTIPOLYGON); MultiPolygon multiPolygon = (MultiPolygon) geometry; TestCase.assertTrue(multiPolygon.hasZ()); TestCase.assertFalse(multiPolygon.hasM()); TestCase.assertEquals(1, multiPolygon.numGeometries()); Polygon polygon = multiPolygon.getPolygon(0); TestCase.assertTrue(polygon.hasZ()); TestCase.assertFalse(polygon.hasM()); TestCase.assertEquals(1, polygon.numRings()); LineString ring = polygon.getRing(0); TestCase.assertTrue(ring.hasZ()); TestCase.assertFalse(ring.hasM()); TestCase.assertEquals(15, ring.numPoints()); for (Point point : ring.getPoints()) { TestCase.assertTrue(point.hasZ()); TestCase.assertFalse(point.hasM()); TestCase.assertNotNull(point.getZ()); TestCase.assertNull(point.getM()); } byte[] multiPolygonBytes = WKBTestUtils.writeBytes(multiPolygon, ByteOrder.LITTLE_ENDIAN); Geometry geometry2 = WKBTestUtils.readGeometry(multiPolygonBytes); geometryTester(geometry, geometry2); TestCase.assertEquals(bytes.length, multiPolygonBytes.length); int equalBytes = 0; for (int i = 0; i < bytes.length; i++) { if (bytes[i] == multiPolygonBytes[i]) { equalBytes++; } } TestCase.assertEquals(bytes.length - 6, equalBytes); } /** * Test geometry finite filtering * * @throws Exception * upon error */ @Test public void testFiniteFilter() throws Exception { Point point = WKBTestUtils.createPoint(false, false); Point nan = new Point(Double.NaN, Double.NaN); Point nanZ = WKBTestUtils.createPoint(true, false); nanZ.setZ(Double.NaN); Point nanM = WKBTestUtils.createPoint(false, true); nanM.setM(Double.NaN); Point nanZM = WKBTestUtils.createPoint(true, true); nanZM.setZ(Double.NaN); nanZM.setM(Double.NaN); Point infinite = new Point(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); Point infiniteZ = WKBTestUtils.createPoint(true, false); infiniteZ.setZ(Double.POSITIVE_INFINITY); Point infiniteM = WKBTestUtils.createPoint(false, true); infiniteM.setM(Double.POSITIVE_INFINITY); Point infiniteZM = WKBTestUtils.createPoint(true, true); infiniteZM.setZ(Double.POSITIVE_INFINITY); infiniteZM.setM(Double.POSITIVE_INFINITY); Point nanInfinite = new Point(Double.NaN, Double.POSITIVE_INFINITY); Point nanInfiniteZM = WKBTestUtils.createPoint(true, true); nanInfiniteZM.setZ(Double.NaN); nanInfiniteZM.setM(Double.NEGATIVE_INFINITY); Point infiniteNan = new Point(Double.POSITIVE_INFINITY, Double.NaN); Point infiniteNanZM = WKBTestUtils.createPoint(true, true); infiniteNanZM.setZ(Double.NEGATIVE_INFINITY); infiniteNanZM.setM(Double.NaN); LineString lineString1 = new LineString(); lineString1.addPoint(point); lineString1.addPoint(nan); lineString1.addPoint(WKBTestUtils.createPoint(false, false)); lineString1.addPoint(infinite); lineString1.addPoint(WKBTestUtils.createPoint(false, false)); lineString1.addPoint(nanInfinite); lineString1.addPoint(WKBTestUtils.createPoint(false, false)); lineString1.addPoint(infiniteNan); LineString lineString2 = new LineString(true, false); lineString2.addPoint(WKBTestUtils.createPoint(true, false)); lineString2.addPoint(nanZ); lineString2.addPoint(WKBTestUtils.createPoint(true, false)); lineString2.addPoint(infiniteZ); LineString lineString3 = new LineString(false, true); lineString3.addPoint(WKBTestUtils.createPoint(false, true)); lineString3.addPoint(nanM); lineString3.addPoint(WKBTestUtils.createPoint(false, true)); lineString3.addPoint(infiniteM); LineString lineString4 = new LineString(true, true); lineString4.addPoint(WKBTestUtils.createPoint(true, true)); lineString4.addPoint(nanZM); lineString4.addPoint(WKBTestUtils.createPoint(true, true)); lineString4.addPoint(infiniteZM); lineString4.addPoint(WKBTestUtils.createPoint(true, true)); lineString4.addPoint(nanInfiniteZM); lineString4.addPoint(WKBTestUtils.createPoint(true, true)); lineString4.addPoint(infiniteNanZM); Polygon polygon1 = new Polygon(lineString1); Polygon polygon2 = new Polygon(lineString2); Polygon polygon3 = new Polygon(lineString3); Polygon polygon4 = new Polygon(lineString4); for (Point pnt : lineString1.getPoints()) { testFiniteFilter(pnt); } for (Point pnt : lineString2.getPoints()) { testFiniteFilter(pnt); } for (Point pnt : lineString3.getPoints()) { testFiniteFilter(pnt); } for (Point pnt : lineString4.getPoints()) { testFiniteFilter(pnt); } testFiniteFilter(lineString1); testFiniteFilter(lineString2); testFiniteFilter(lineString3); testFiniteFilter(lineString4); testFiniteFilter(polygon1); testFiniteFilter(polygon2); testFiniteFilter(polygon3); testFiniteFilter(polygon4); } /** * Test the geometry writing to and reading from bytes * * @param geometry * geometry * @throws IOException */ private void geometryTester(Geometry geometry) throws IOException { geometryTester(geometry, geometry); } /** * Test the geometry writing to and reading from bytes, compare with the * provided geometry * * @param geometry * geometry * @param compareGeometry * compare geometry * @throws IOException */ private void geometryTester(Geometry geometry, Geometry compareGeometry) throws IOException { // Write the geometries to bytes byte[] bytes1 = WKBTestUtils.writeBytes(geometry, ByteOrder.BIG_ENDIAN); byte[] bytes2 = WKBTestUtils.writeBytes(geometry, ByteOrder.LITTLE_ENDIAN); TestCase.assertFalse(WKBTestUtils.equalByteArrays(bytes1, bytes2)); // Test that the bytes are read using their written byte order, not // the specified Geometry geometry1opposite = WKBTestUtils.readGeometry(bytes1, ByteOrder.LITTLE_ENDIAN); Geometry geometry2opposite = WKBTestUtils.readGeometry(bytes2, ByteOrder.BIG_ENDIAN); WKBTestUtils.compareByteArrays(WKBTestUtils.writeBytes(compareGeometry), WKBTestUtils.writeBytes(geometry1opposite)); WKBTestUtils.compareByteArrays(WKBTestUtils.writeBytes(compareGeometry), WKBTestUtils.writeBytes(geometry2opposite)); Geometry geometry1 = WKBTestUtils.readGeometry(bytes1, ByteOrder.BIG_ENDIAN); Geometry geometry2 = WKBTestUtils.readGeometry(bytes2, ByteOrder.LITTLE_ENDIAN); WKBTestUtils.compareGeometries(compareGeometry, geometry1); WKBTestUtils.compareGeometries(compareGeometry, geometry2); WKBTestUtils.compareGeometries(geometry1, geometry2); GeometryEnvelope envelope = GeometryEnvelopeBuilder .buildEnvelope(compareGeometry); GeometryEnvelope envelope1 = GeometryEnvelopeBuilder .buildEnvelope(geometry1); GeometryEnvelope envelope2 = GeometryEnvelopeBuilder .buildEnvelope(geometry2); WKBTestUtils.compareEnvelopes(envelope, envelope1); WKBTestUtils.compareEnvelopes(envelope1, envelope2); } /** * Convert the hex string to a byte array * * @param hex * hex string * @return byte array */ private static byte[] hexStringToByteArray(String hex) { int len = hex.length(); byte[] bytes = new byte[len / 2]; for (int i = 0; i < len; i += 2) { bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return bytes; } /** * Test fine filter for the geometry * * @param geometry * geometry * @throws Exception */ private void testFiniteFilter(Geometry geometry) throws Exception { ByteWriter writer = new ByteWriter(); GeometryWriter.writeGeometry(writer, geometry); byte[] bytes = writer.getBytes(); testFiniteFilter(bytes, new PointFiniteFilter()); testFiniteFilter(bytes, new PointFiniteFilter(true)); testFiniteFilter(bytes, new PointFiniteFilter(false, true)); testFiniteFilter(bytes, new PointFiniteFilter(true, true)); testFiniteFilter(bytes, new PointFiniteFilter(FiniteFilterType.FINITE_AND_NAN)); testFiniteFilter(bytes, new PointFiniteFilter(FiniteFilterType.FINITE_AND_NAN, true)); testFiniteFilter(bytes, new PointFiniteFilter( FiniteFilterType.FINITE_AND_NAN, false, true)); testFiniteFilter(bytes, new PointFiniteFilter( FiniteFilterType.FINITE_AND_NAN, true, true)); testFiniteFilter(bytes, new PointFiniteFilter(FiniteFilterType.FINITE_AND_INFINITE)); testFiniteFilter(bytes, new PointFiniteFilter( FiniteFilterType.FINITE_AND_INFINITE, true)); testFiniteFilter(bytes, new PointFiniteFilter( FiniteFilterType.FINITE_AND_INFINITE, false, true)); testFiniteFilter(bytes, new PointFiniteFilter( FiniteFilterType.FINITE_AND_INFINITE, true, true)); } /** * Filter and validate the geometry bytes * * @param bytes * geometry bytes * @param filter * point finite filter * @throws IOException * upon error */ private void testFiniteFilter(byte[] bytes, PointFiniteFilter filter) throws IOException { ByteReader reader = new ByteReader(bytes); Geometry geometry = GeometryReader.readGeometry(reader, filter); reader.close(); if (geometry != null) { List<Point> points = new ArrayList<>(); switch (geometry.getGeometryType()) { case POINT: points.add((Point) geometry); break; case LINESTRING: points.addAll(((LineString) geometry).getPoints()); break; case POLYGON: points.addAll(((Polygon) geometry).getRing(0).getPoints()); break; default: TestCase.fail( "Unexpected test case: " + geometry.getGeometryType()); } for (Point point : points) { switch (filter.getType()) { case FINITE: TestCase.assertTrue(Double.isFinite(point.getX())); TestCase.assertTrue(Double.isFinite(point.getY())); if (filter.isFilterZ() && point.hasZ()) { TestCase.assertTrue(Double.isFinite(point.getZ())); } if (filter.isFilterM() && point.hasM()) { TestCase.assertTrue(Double.isFinite(point.getM())); } break; case FINITE_AND_NAN: TestCase.assertTrue(Double.isFinite(point.getX()) || Double.isNaN(point.getX())); TestCase.assertTrue(Double.isFinite(point.getY()) || Double.isNaN(point.getY())); if (filter.isFilterZ() && point.hasZ()) { TestCase.assertTrue(Double.isFinite(point.getZ()) || Double.isNaN(point.getZ())); } if (filter.isFilterM() && point.hasM()) { TestCase.assertTrue(Double.isFinite(point.getM()) || Double.isNaN(point.getM())); } break; case FINITE_AND_INFINITE: TestCase.assertTrue(Double.isFinite(point.getX()) || Double.isInfinite(point.getX())); TestCase.assertTrue(Double.isFinite(point.getY()) || Double.isInfinite(point.getY())); if (filter.isFilterZ() && point.hasZ()) { TestCase.assertTrue(Double.isFinite(point.getZ()) || Double.isInfinite(point.getZ())); } if (filter.isFilterM() && point.hasM()) { TestCase.assertTrue(Double.isFinite(point.getM()) || Double.isInfinite(point.getM())); } break; } } } } }
package org.ms2ms.math; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Range; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; import org.apache.commons.math3.stat.regression.SimpleRegression; import org.ms2ms.data.Point; import org.ms2ms.utils.Tools; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class Points { /** Simple linear interpolation * * @param p1 * @param p2 * @param x * @return xy.getY() = the interpolated Y */ public static <T extends Point> T interpolate(T p1, T p2, Double x) { T xy = (T )(new Point(x, 0d)); if (p1 != null && p2 == null) { //xy.setY(p1.getY()); xy = null; // undefined situation, WYU 081209 } else if (p1 == null && p2 != null) { //xy.setY(p2.getY()); xy = null; } else if (p1 != null && p2 != null && p2.getX() - p1.getX() != 0) { Double k = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()); xy.setY(p1.getY() + (x - p1.getX()) * k); } else if (p1 != null && p2 != null && p2.getX() == p1.getX()) { Double k = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()); xy.setY(0.5d * (p1.getY() + p2.getY())); } return xy; } public static <T extends Point> T interpolateByY(T p1, T p2, Double y) { T xy = (T )(new Point(0d, y)); if (p1 == null || p2 == null) { //xy.setY(p1.getY()); xy = null; // undefined situation, WYU 081209 } else if (p2.getX() - p1.getX() != 0) { Double k = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()); xy.setX(p1.getX() + (y-p1.getY()) / k); } else if (p2.getX() == p1.getX()) { Double k = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()); xy.setY(0.5d * (p1.getY() + p2.getY())); } // in case where the interpolation fail, take the conservative default if (Double.isInfinite(xy.getX())) xy.setX(0.5d*(p1.getX()+p2.getX())); return xy; } public static <T extends Point> T interpolate(List<T> ps, Double x, boolean ignore_zero) { Range<T> range = boundry((T )(new Point(x, 0d)), ps, ignore_zero); return range != null ? interpolate(range.lowerEndpoint(), range.upperEndpoint(), x) : null; } /* // extend a few points beyond the boundry and estimate the uncertainty of the interpolation accordingly public static <T extends Point> MsReporter interpolate(List<T> ps, Double x, boolean ignore_zero, int extension) { //Range<T> range = findBoundry((T )(new Point(x, 0d)), ps, ignore_zero); Multimap<Integer, T> range = Point_Util.findBoundry((T )(new Point(x, 0d)), ps, ignore_zero, extension); if (range == null) return null; Collection<Double> estimates = new ArrayList<Double>(); for (T left : range.get(-1)) { for (T right : range.get(1)) { T estimated = interpolate(left, right, x); estimates.add(estimated.getY()); } } return new MsReporterIon(x, Toolbox.mean(estimates), 1.96d * Toolbox.stdev(estimates)); } */ /** Returns the base peak (the peak with the highest relative intensity) of the spectrum. */ public static <T extends Point> T basePoint(Collection<T> data) { if (!Tools.isSet(data)) return null; T base = null; for (T datum : data) if (base == null || (datum.getY() > base.getY())) base = datum; // send the base peak back return base; } public static <T extends Point> T basePoint(List<T> data, int pad) { if (!Tools.isSet(data)) return null; int top = -1; T best = null; for (int i = 0; i < data.size(); i++) if (top == -1 || (data.get(i).getY() > best.getY())) { best = data.get(i); top = i; } if (top == -1) return null; Collection<T> profile = new ArrayList<T>(); for (int i = top; i <= top + pad; i++) if (i < data.size()) profile.add(data.get(i)); for (int i = top - 1; i >= top - pad; i--) if (i >= 0) profile.add(data.get(i)); // send the base peak back return (T)(new Point(centroid(profile), best.getY())); } /** Assuming asending order in X * * @param m * @param ms * @param ignore_zero * @return lower, upper */ public static <T extends Point> Range<T> boundry(T m, List<T> ms, boolean ignore_zero) { // locate the point that's the cloest to 'm' int index = Collections.binarySearch(ms, m), left, right; if (index >= 0) { left = index; right = index; } else // (-(insertion point) - 1) { index = -1 * index - 1; left = (index > 0 ? index-1 : -1); right = (index < ms.size() ? index : -1); } if (ignore_zero && left >= 0 && ms.get(left).getY() == 0) for (int i = left; i >= 0; i--) if (ms.get(i).getY() != 0) { left = i; break; } if (ignore_zero && right >= 0 && ms.get(right).getY() == 0) for (int i = right; i < ms.size(); i++) if (ms.get(i).getY() != 0) { right = i; break; } return (left >= 0 && right >= left ? Range.closed(ms.get(left), ms.get(right)) : null); } public static <T extends Point> Multimap<Integer, T> boundry(T m, List<T> ms, boolean ignore_zero, int extension) { // locate the point that's the cloest to 'm' int index = Collections.binarySearch(ms, m), left, right; if (index >= 0) { left = index; right = index; } else // (-(insertion point) - 1) { index = -1 * index - 1; left = (index > 0 ? index-1 : -1); right = (index < ms.size() ? index : -1); } Multimap<Integer, T> boundary = HashMultimap.create(); for (int i = left; i >= 0; i if (!ignore_zero || ms.get(i).getY() != 0) { boundary.put(-1, ms.get(i)); // quite if we have enough point already if (boundary.get(-1).size() >= extension) break; } for (int i = right; i < ms.size(); i++) if (!ignore_zero || (i >= 0 && ms.get(i).getY() != 0)) { boundary.put(1, ms.get(i)); // quite if we have enough point already if (boundary.get(1).size() >= extension) break; } return boundary; } public static Range<Point> boundry(Double x0, Double x1, int start, List<? extends Point> points, Range<Point> range) { // doing nothing if (x0 == null || x1 == null || x1 < x0) return range; Point lower=range.lowerEndpoint(), upper=range.upperEndpoint(); for (int k = start; k < points.size(); k++) { if (points.get(k).getX() >= x0) { start = k; lower=points.get(k); for (int i = start; i < points.size(); i++) { if (points.get(i).getX() >= x1) { // let's interpolate the numbers upper=points.get(i); return Range.closed(lower, upper); } } } } return range; } public static <T extends Point> Double centroid(Collection<T> points) { return centroid(points, (Double )null, (Double )null); } public static <T extends Point> Double centroid(Collection<T> points, Double x0, Double x1) { if (! Tools.isSet(points)) return null; double sumXY = 0, sumY = 0; for (Point xy : points) { if ((x0 == null || xy.getX() >= x0) && (x1 == null || xy.getX() <= x1)) { sumXY += xy.getX() * xy.getY(); sumY += xy.getY(); } } return sumY != 0 ? sumXY / sumY : null; } public static <T extends Point> Point centroid(Collection<T> points, Double min_ri, Range<Double> x_range) { if (!Tools.isSet(points)) return null; Point top = getBasePoint(points, x_range); if (top==null) return null; double sumXY=0, sumY=0, sumX=0,N=0, base = top.getY(), min_ai = base*min_ri*0.01; for (Point xy : points) { if ((x_range==null || x_range.contains(xy.getX())) && xy.getY()>min_ai) { sumXY += xy.getX() * xy.getY(); sumY += xy.getY(); sumX += xy.getX(); N++; } } if (sumY!=0) return new Point(sumXY / sumY, base); else { // System.out.println(); return null; } } public static <T extends Point> T getBasePoint(Collection<T> data) { if (!Tools.isSet(data)) return null; T base = null; for (T datum : data) if (base == null || (datum.getY() > base.getY())) base = datum; // send the base peak back return base; } public static <T extends Point> T getBasePoint(Collection<T> data, Range<Double> range) { if (!Tools.isSet(data)) return null; T base = null; for (T datum : data) if ((range==null || range.contains(datum.getX())) && (base == null || (datum.getY() > base.getY()))) base = datum; // send the base peak back return base; } public static <T extends Point> Double sumY(Collection<T> data) { if (data==null) return null; double sum = 0d; for (T xy : data) sum += xy.getY(); return sum; } public static <T extends Point> Double sumY(List<T> data, int i0) { if (data==null) return null; double sum = 0d; for (int i=i0; i<data.size(); i++) sum += data.get(i).getY(); return sum; } public static <T extends Point> List<Double> toYs(List<T> data) { if (Tools.isSet(data)) { List<Double> ys = new ArrayList<>(data.size()); for (T xy : data) ys.add(xy.getY()); return ys; } return null; } public static <T extends Point> int findClosest(List<T> pts, double x) { if (pts==null) return -1; int best=-1; for (int i=0; i<pts.size(); i++) if (best==-1 || Math.abs(pts.get(i).getX()-x) < Math.abs(pts.get(i).getX()-pts.get(best).getX())) { best=i; } return best; } private Double quadratic(Collection<Point> pts) { double[] mCoeffs=null; if (pts!=null&&pts.size()>4) { List<WeightedObservedPoint> points=new ArrayList<>(pts.size()); for (Point pt : pts) points.add(new WeightedObservedPoint(1, pt.getX(), pt.getY())); // fit a polynomial curve PolynomialCurveFitter quad=PolynomialCurveFitter.create(2); mCoeffs=quad.fit(points); double d=(mCoeffs[1]*mCoeffs[1]-4*mCoeffs[0]*mCoeffs[2]), x1=(-1*mCoeffs[1]-Math.sqrt(d))/(2*mCoeffs[2]), x2=(-1*mCoeffs[1]+Math.sqrt(d))/(2*mCoeffs[2]); // picking the lowest of the roots return Math.min(x1, x2); // // inter/ex-polating for the critical score // int left=(int )Math.floor(mThreshold), right=(int )Math.ceil(mThreshold); // Point x = Points.interpolate(new Point(left, scores.get(left)), new Point(right, scores.get(right)), mThreshold); // mThreshold = x.getY(); } return null; } private Double extremeCum(Collection<Point> pts) { double[] mCoeffs=null; if (pts!=null&&pts.size()>4) { List<WeightedObservedPoint> points=new ArrayList<>(pts.size()); for (Point pt : pts) points.add(new WeightedObservedPoint(1, pt.getX(), pt.getY())); // fit a polynomial curve PolynomialCurveFitter quad=PolynomialCurveFitter.create(2); mCoeffs=quad.fit(points); double d=(mCoeffs[1]*mCoeffs[1]-4*mCoeffs[0]*mCoeffs[2]), x1=(-1*mCoeffs[1]-Math.sqrt(d))/(2*mCoeffs[2]), x2=(-1*mCoeffs[1]+Math.sqrt(d))/(2*mCoeffs[2]); // picking the lowest of the roots return Math.min(x1, x2); // // inter/ex-polating for the critical score // int left=(int )Math.floor(mThreshold), right=(int )Math.ceil(mThreshold); // Point x = Points.interpolate(new Point(left, scores.get(left)), new Point(right, scores.get(right)), mThreshold); // mThreshold = x.getY(); } return null; } private Double linear(Collection<Point> pts, int limit) { if (pts!=null&&pts.size()>2) { // settle for a linear fit SimpleRegression linear=new SimpleRegression(true); for (Point pt : pts) if (linear.getN()<limit) linear.addData(pt.getX(), pt.getY()); return -1*linear.getIntercept()/linear.getSlope(); } return null; } }
package org.wikipedia; import java.io.*; import java.net.URLEncoder; import java.util.*; import java.util.logging.*; /** * Stuff specific to Wikimedia wikis. * @author MER-C * @version 0.01 */ public class WMFWiki extends Wiki { /** * Creates a new WMF wiki that represents the English Wikipedia. */ public WMFWiki() { super("en.wikipedia.org"); } /** * Creates a new WMF wiki that has the given domain name. * @param domain a WMF wiki domain name e.g. en.wikipedia.org */ public WMFWiki(String domain) { super(domain); } /** * Returns the list of publicly readable and editable wikis operated by the * Wikimedia Foundation. * @return (see above) * @throws IOException if a network error occurs */ public static WMFWiki[] getSiteMatrix() throws IOException { WMFWiki wiki = new WMFWiki("en.wikipedia.org"); wiki.setMaxLag(0); String line = wiki.fetch("http://en.wikipedia.org/w/api.php?format=xml&action=sitematrix", "WMFWiki.getSiteMatrix"); ArrayList<WMFWiki> wikis = new ArrayList<WMFWiki>(1000); for (int x = line.indexOf("url=\""); x >= 0; x = line.indexOf("url=\"", x)) { int a = line.indexOf("http://", x) + 7; int b = line.indexOf('\"', a); int c = line.indexOf("/>", b); x = c; // check for closed/fishbowl/private wikis String temp = line.substring(b, c); if (temp.contains("closed=\"\"") || temp.contains("private=\"\"") || temp.contains("fishbowl=\"\"")) continue; wikis.add(new WMFWiki(line.substring(a, b))); } int size = wikis.size(); Logger temp = Logger.getLogger("wiki"); temp.log(Level.INFO, "WMFWiki.getSiteMatrix", "Successfully retrieved site matrix (" + size + " + wikis)."); return wikis.toArray(new WMFWiki[size]); } /** * Get the global usage for a file (requires extension GlobalUsage). * * @param title the title of the page (must contain "File:") * @return the global usage of the file, including the wiki and page the file is used on * @throws IOException if a network error occurs * @throws UnsupportedOperationException if <tt>namespace(title) != FILE_NAMESPACE</tt> */ public String[][] getGlobalUsage(String title) throws IOException { title = normalize(title); if (namespace(title) != FILE_NAMESPACE) throw new UnsupportedOperationException("Cannot retrieve Globalusage for pages other than File pages!"); String url = query + "prop=globalusage&gulimit=max&titles=" + URLEncoder.encode(title, "UTF-8"); String next = ""; ArrayList<String[]> usage = new ArrayList<>(500); do { if (!next.isEmpty()) next = "&gucontinue=" + URLEncoder.encode(next, "UTF-8"); String line = fetch(url+next, "getGlobalUsageCount"); // parse gucontinue if it is there if (line.contains("<query-continue>")) next = parseAttribute(line, "gucontinue", 0); else next = null; for (int i = line.indexOf("<gu"); i > 0; i = line.indexOf("<gu", ++i)) usage.add(new String[] { parseAttribute(line, "wiki", i), parseAttribute(line, "title", i) }); } while (next != null); return usage.toArray(new String[0][0]); } }
package org.async.rmi; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.rmi.RemoteException; import java.util.concurrent.CompletableFuture; public class ExampleServer implements Example { private static final Logger logger = LoggerFactory.getLogger(ExampleServer.class); @Override public String echo(String msg) throws RemoteException { logger.debug("Server: called echo({})", msg); return msg; } @Override public CompletableFuture<String> futuredEcho(final String msg) throws RemoteException { logger.debug("Server: futuredEcho echo({})", msg); return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(e.toString(), e); } return msg; }); } public static void main(String[] args) throws Exception { try { ExampleServer server = new ExampleServer(); Example proxy = (Example) Modules.getInstance().getExporter().export(server); File file = new File("ExampleServer.proxy"); Util.serialize(Files.asByteSink(file), proxy); logger.info("proxy {} saved to file {}, server is running at: {}:{}", proxy, file.getAbsolutePath()); } catch (Exception e) { logger.error("ExampleServer exception while exporting:", e); } File file = new File("ExampleServer.proxy"); //noinspection UnusedDeclaration Example example = (Example) Util.deserialize(Files.asByteSource(file)); String res = example.echo("foo"); logger.info("client got: {}", res); res = example.echo("foo1"); logger.info("client got: {}", res); CompletableFuture<String> future = example.futuredEcho("async foo"); res = future.join(); logger.debug("client got async res : {}", res); } }
package pathfinding; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PathfindingTest { private static final Logger logger = LoggerFactory.getLogger( PathfindingTest.class ); public PathfindingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } public static Node[][] makeNodes() { int multiplier = 5; int width = 100; int height = 100; Node[][] nodes = new Node[ width ][ height ]; for( int x = 0; x < width; x++ ){ for( int y = 0; y < height; y++ ){ int xx = x * multiplier; int yy = y * multiplier; Node node = new Node(xx, yy, x, y); nodes[x][y] = node; } } return nodes; } @Test public void testDistance() throws Exception{ double expected = 14.142; double delta = 0.01; int x1 = 0; int y1 = 0; int x2 = 10; int y2 = 10; double distance = Vertex.distance( x1, y1, x2, y2 ); Assert.assertEquals( expected, distance, delta ); Vertex one = new Vertex( x1, y1 ); Vertex two = new Vertex( x2, y2 ); distance = Vertex.distance( one, two ); Assert.assertEquals( expected, distance, delta ); } private static void runTest( Node[][] nodes, Vertex start, Vertex end ) throws Exception{ long startTime = System.currentTimeMillis(); List<Node> dijkstra = Pathfinder.dijkstra(nodes, start, end ); long endTime = System.currentTimeMillis(); long dTime = (endTime - startTime); startTime = System.currentTimeMillis(); List<Node> astar = Pathfinder.bestFirst(nodes, start, end ); endTime = System.currentTimeMillis(); long bfTime = (endTime - startTime); // logger.info( "Dijkstra" ); // Pathfinder.printPath( nodes, dijkstra ); // logger.info( "A*" ); // Pathfinder.printPath( nodes, astar ); logger.info( "Same solution: " + dijkstra.equals( astar ) ); logger.info( "Dijkstra time: " + dTime + " ms" ); logger.info( "Best First time : " + bfTime + " ms" ); logger.info( "" ); } @Test public void testOne() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); runTest( nodes, start, end ); } @Test public void testTwo() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); runTest( nodes, start, end ); } @Test public void testTwoA() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-3, nodes[0].length-2); runTest( nodes, start, end ); } @Test public void testTwoB() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( 5, 3 ); runTest( nodes, start, end ); } @Test public void testThree() throws Exception { Node[][] nodes = makeNodes(); nodes[0][8].traversable = false; nodes[1][8].traversable = false; nodes[2][8].traversable = false; nodes[3][8].traversable = false; nodes[9][2].traversable = false; nodes[8][2].traversable = false; nodes[7][2].traversable = false; nodes[6][2].traversable = false; nodes[2][4].traversable = false; nodes[3][4].traversable = false; nodes[4][4].traversable = false; nodes[5][4].traversable = false; Vertex start = new Vertex(9,0); Vertex end = new Vertex(0,9); runTest( nodes, start, end ); } @Test public void testFour() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[5][2].traversable = false; nodes[5][3].traversable = false; nodes[5][4].traversable = false; nodes[5][5].traversable = false; Vertex start = new Vertex(0,2); Vertex end = new Vertex(9,9); runTest( nodes, start, end ); } @Test public void testFive() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; nodes[1][2].traversable = false; nodes[1][3].traversable = false; nodes[1][4].traversable = false; nodes[1][5].traversable = false; nodes[1][6].traversable = false; nodes[1][7].traversable = false; nodes[1][8].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex(2,0); runTest( nodes, start, end ); } @Test public void testSix() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( 1,1 ); runTest( nodes, start, end ); } @Test public void testSeven() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(5,5); Vertex end = new Vertex(5,5); runTest( nodes, start, end ); } }
/** * @file 2016/12/08 */ package quiz.model; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import org.dbunit.database.DatabaseConfig; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.ext.mysql.MySqlDataTypeFactory; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * MySQL * * @author Yuka Yoshikawa * */ public class SqlDataStoreTest { /** Connectionn */ private java.lang.reflect.Field con; /** SqlDataStorepassword */ private java.lang.reflect.Field pass; // /** DBUnitConnection */ // private IDatabaseConnection dbconn; // // private File file; /** MySQL */ private SqlDataStore sds; /** * * * @throws java.lang.Exception */ @Before public void setUp() throws Exception { sds = new SqlDataStore(); java.sql.Connection connection = getConnection(); /** SqlDataStoreConnection */ pass = SqlDataStore.class.getDeclaredField("pass"); pass.setAccessible(true); pass.set(sds, ""); /** SqlDataStorepassword */ con = SqlDataStore.class.getDeclaredField("con"); con.setAccessible(true); con.set(sds, connection); IDatabaseConnection dbconn = new DatabaseConnection(connection); DatabaseConfig config = dbconn.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory()); // // QueryDataSet partialDataSet = new QueryDataSet(dbconn); // partialDataSet.addTable("englishword"); // file = File.createTempFile("escape", ".xml"); // FlatXmlDataSet.write(partialDataSet, new FileOutputStream(file)); // /** XmlDB */ // IDataSet dataset = new FlatXmlDataSetBuilder().build(new // File("testData.xml")); // DatabaseOperation.CLEAN_INSERT.execute(dbconn, dataset); } /** * DB * * @return testDBconnection * @throws SQLException * @throws ClassNotFoundException */ public static java.sql.Connection getConnection() throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://localhost/test", "root", ""); } /** * * * @throws java.lang.Exception */ @After public void tearDown() throws Exception { // dbconn = new DatabaseConnection(getConnection()); // // IDataSet dataset = new FlatXmlDataSetBuilder().build(file); // DatabaseOperation.CLEAN_INSERT.execute(dbconn, dataset); if (con != null) { sds.close(); } } /** * {@link quiz.model.SqlDataStore#open()} * * @note */ @Test public void testOpen() { try { sds.open(); sds.close(); } catch (Exception e) { fail(e.getMessage()); } } /** * {@link quiz.model.SqlDataStore#close()} * * @note */ @Test public void testClose() { try { sds.open(); sds.close(); } catch (Exception e) { fail(e.getMessage()); } } /** * {@link quiz.model.SqlDataStore#getAll()} * * @note testDBenglishword */ @Test public void testGetAll() { try { ArrayList<EnglishWordBean> list = sds.getAll(); assertThat(list.size(), is(4)); assertThat(list.get(3).getId(), is(4)); assertThat(list.get(0).getWord(), is("apple")); assertThat(list.get(2).getPart(), is(Part.getPart(""))); } catch (Exception e) { fail(e.getMessage()); } } /** * {@link quiz.model.SqlDataStore#insert()} * * @note testDBenglishword1 */ @Test public void testInsert() { try { EnglishWordBean bean = new EnglishWordBean(); bean.setWord("soccer"); bean.setPart(Part.getPart("")); bean.setMean(""); sds.insert(bean); ArrayList<EnglishWordBean> list = sds.getAll(); assertThat(list.get(list.size() - 1).getWord(), is("soccer")); assertThat(list.get(list.size() - 1).getPart(), is(Part.getPart(""))); assertThat(list.get(list.size() - 1).getMean(), is("")); } catch (Exception e) { fail(e.getMessage()); } } /** * {@link quiz.model.SqlDataStore#update(quiz.model.EnglishWordBean)} * */ @Ignore public void testUpdate() { fail(""); // TODO } /** * {@link quiz.model.SqlDataStore#delete(quiz.model.EnglishWordBean)} * */ @Ignore public void testDelete() { fail(""); // TODO } /** * {@link quiz.model.SqlDataStore#searchWord()} * * @note testDBenglishword1 */ @Test public void testSearchWord() { try { EnglishWordBean bean = new EnglishWordBean(); bean.setWord("cat"); bean.setMean(""); assertNotNull(sds.searchWord(bean)); } catch (Exception e) { fail(e.getMessage()); } } /** * {@link quiz.model.SqlDataStore#getRandom()} * * @note testDBenglishword1 */ @Test public void testGetRandom() { try { EnglishWordBean resultBean = sds.getRandom(); assertNotNull(resultBean); } catch (Exception e) { fail(e.getMessage()); } } }
package tars.logic; import com.google.common.eventbus.Subscribe; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import tars.commons.core.Config; import tars.commons.core.EventsCenter; import tars.commons.core.Messages; import tars.commons.events.model.TarsChangedEvent; import tars.commons.events.ui.JumpToListRequestEvent; import tars.commons.events.ui.ShowHelpRequestEvent; import tars.commons.exceptions.DataConversionException; import tars.commons.flags.Flag; import tars.commons.util.ConfigUtil; import tars.logic.Logic; import tars.logic.LogicManager; import tars.logic.commands.AddCommand; import tars.logic.commands.CdCommand; import tars.logic.commands.ClearCommand; import tars.logic.commands.Command; import tars.logic.commands.CommandResult; import tars.logic.commands.DeleteCommand; import tars.logic.commands.EditCommand; import tars.logic.commands.ExitCommand; import tars.logic.commands.FindCommand; import tars.logic.commands.HelpCommand; import tars.logic.commands.ListCommand; import tars.logic.commands.MarkCommand; import tars.logic.commands.SelectCommand; import tars.logic.commands.UndoCommand; import tars.model.Tars; import tars.model.Model; import tars.model.ModelManager; import tars.model.ReadOnlyTars; import tars.model.task.*; import tars.model.tag.Tag; import tars.model.tag.UniqueTagList; import tars.storage.StorageManager; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static tars.commons.core.Messages.*; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; private Config originalConfig; private static final String configFilePath = "config.json"; // These are for checking the correctness of the events raised private ReadOnlyTars latestSavedTars; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TarsChangedEvent abce) { latestSavedTars = new Tars(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setup() { try { originalConfig = ConfigUtil.readConfig(configFilePath).get(); } catch (DataConversionException e) { System.out.println("Config File cannot be found"); e.printStackTrace(); } model = new ModelManager(); String tempTarsFile = saveFolder.getRoot().getPath() + "TempTars.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTarsFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTars = new Tars(model.getTars()); // last saved assumed to be // up to date before. helpShown = false; targetedJumpIndex = -1; // non yet } @After public void teardown() throws IOException { undoChangeInTarsFilePath(); EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command and confirms that the result message is correct. * Both the 'tars' and the 'last shown list' are expected to be empty. * * @see #assertCommandBehavior(String, String, ReadOnlyTars, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new Tars(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's * state are as expected:<br> * - the internal tars data are same as those in the {@code expectedTars} * <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedTars} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyTars expectedTars, List<? extends ReadOnlyTask> expectedShownList) throws Exception { // Execute the command CommandResult result = logic.execute(inputCommand); // Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTars, model.getTars()); assertEquals(expectedTars, latestSavedTars); } @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws Exception { assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new Tars(), Collections.emptyList()); } @Test public void execute_undo_emptyCmdHistStack() throws Exception { assertCommandBehavior("undo", UndoCommand.MESSAGE_EMPTY_UNDO_CMD_HIST); } @Test public void execute_undo_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeUndo = helper.meetAdam(); Tars expectedAB = new Tars(); expectedAB.addTask(toBeUndo); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeUndo), String.format(AddCommand.MESSAGE_SUCCESS, toBeUndo), expectedAB, expectedAB.getTaskList()); expectedAB.removeTask(toBeUndo); assertCommandBehavior("undo", UndoCommand.MESSAGE_SUCCESS + "\nAction: " + String.format(AddCommand.MESSAGE_UNDO, toBeUndo), expectedAB, expectedAB.getTaskList()); } @Test public void execute_undo_delete_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeUndo = helper.meetAdam(); Tars expectedAB = new Tars(); expectedAB.addTask(toBeUndo); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeUndo), String.format(AddCommand.MESSAGE_SUCCESS, toBeUndo), expectedAB, expectedAB.getTaskList()); expectedAB.removeTask(toBeUndo); // execute command and verify result assertCommandBehavior("del 1", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, toBeUndo), expectedAB, expectedAB.getTaskList()); expectedAB.addTask(toBeUndo); assertCommandBehavior("undo", UndoCommand.MESSAGE_SUCCESS + "\nAction: " + String.format(DeleteCommand.MESSAGE_UNDO, toBeUndo), expectedAB, expectedAB.getTaskList()); } @Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior("add -dt 22/04/2016 1400 to 23/04/2016 2200 -p h Valid Task Name", expectedMessage); assertCommandBehavior("add", expectedMessage); } @Test public void execute_add_invalidTaskData() throws Exception { assertCommandBehavior("add []\\[;] -dt 05/09/2016 1400 to 06/09/2016 2200 -p m", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandBehavior("add name - hello world -dt 05/09/2016 1400 to 06/09/2016 2200 -p m", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandBehavior("add Valid Task Name -dt @@@notAValidDate@@@ -p m", Messages.MESSAGE_INVALID_DATE); assertCommandBehavior("add Valid Task Name -dt 05/09/2016 1400 to 06/09/2016 2200 -p medium", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandBehavior("add Valid Task Name -dt 05/09/2016 1400 to 06/09/2016 2200 -p m -t invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.meetAdam(); Tars expectedAB = new Tars(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_add_float_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.floatTask(); Tars expectedAB = new Tars(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.meetAdam(); Tars expectedAB = new Tars(); expectedAB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // task already in internal address book // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); } @Test public void execute_listInvalidFlags_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("ls -", expectedMessage); } /** * Test for list command * * @@author A0140022H * @throws Exception */ @Test public void execute_list_showsAllUndoneTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); Tars expectedAB = helper.generateTars(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare tars state helper.addToModel(model, 2); assertCommandBehavior("ls", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Test for list done command * * @@author A0140022H * @throws Exception */ @Test public void execute_list_showsAllDoneTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); Tars expectedAB = new Tars(); Task task1 = helper.meetAdam(); Status done = new Status(true); task1.setStatus(done); List<Task> taskList = new ArrayList<Task>(); taskList.add(task1); expectedAB.addTask(task1); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare tars state helper.addToModel(model, taskList); assertCommandBehavior("ls -do", ListCommand.MESSAGE_SUCCESS_DONE, expectedAB, expectedList); } /** * Test for list all command * * @@author A0140022H * @throws Exception */ @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); Tars expectedAB = helper.generateTars(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare tars state helper.addToModel(model, 2); assertCommandBehavior("ls -all", ListCommand.MESSAGE_SUCCESS_ALL, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord, expectedMessage); // index missing assertCommandBehavior(commandWord + " +1", expectedMessage); // index // should // unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); // index // should // unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); // index // cannot be assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new Tars()); for (Task p : taskList) { model.addTask(p); } if (commandWord == "edit") { // Only For Edit Command assertCommandBehavior(commandWord + " 3 -n changeTaskName", expectedMessage, model.getTars(), taskList); } else { // For Select & Delete Commands assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTars(), taskList); } } // @@author A0124333U private void assertInvalidInputBehaviorForEditCommand(String inputCommand, String expectedMessage) throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new Tars()); for (Task p : taskList) { model.addTask(p); } assertCommandBehavior(inputCommand, expectedMessage, model.getTars(), taskList); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); Tars expectedAB = helper.generateTars(threeTasks); helper.addToModel(model, threeTasks); assertCommandBehavior("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("del ", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("del"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); Tars expectedAB = helper.generateTars(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandBehavior("del 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); Tars expectedAB = helper.generateTars(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); String searchKeywords = "\nQuick Search Keywords: [KEY]"; assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); Tars expectedAB = helper.generateTars(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); String searchKeywords = "\nQuick Search Keywords: [KEY]"; assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedAB, expectedList); } @Test public void execute_find_matchesIfAllKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key rAnDoM"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); Tars expectedAB = helper.generateTars(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget3); helper.addToModel(model, fourTasks); String searchKeywords = "\nQuick Search Keywords: [key, rAnDoM]"; assertCommandBehavior("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedAB, expectedList); } // @@author A0124333U @Test public void execute_edit_invalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE); assertInvalidInputBehaviorForEditCommand("edit ", expectedMessage); assertInvalidInputBehaviorForEditCommand("edit 1 -invalidFlag invalidArg", expectedMessage); } @Test public void execute_edit_indexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("edit"); } @Test public void execute_edit_invalidTaskData() throws Exception { assertInvalidInputBehaviorForEditCommand("edit 1 -n []\\[;]", Name.MESSAGE_NAME_CONSTRAINTS); assertInvalidInputBehaviorForEditCommand("edit 1 -dt @@@notAValidDate@@@", Messages.MESSAGE_INVALID_DATE); assertInvalidInputBehaviorForEditCommand("edit 1 -p medium", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertInvalidInputBehaviorForEditCommand("edit 1 -n validName -dt invalidDate", Messages.MESSAGE_INVALID_DATE); assertInvalidInputBehaviorForEditCommand("edit 1 -tr $#$", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_edit_editsCorrectTask() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task taskToAdd = helper.meetAdam(); List<Task> listToEdit = new ArrayList<Task>(); listToEdit.add(taskToAdd); Tars expectedAB = new Tars(); expectedAB.addTask(taskToAdd); Flag nameOpt = new Flag(Flag.NAME, false); Flag priorityOpt = new Flag(Flag.PRIORITY, false); Flag dateTimeOpt = new Flag(Flag.DATETIME, false); Flag addTagOpt = new Flag(Flag.ADDTAG, true); Flag removeTagOpt = new Flag(Flag.REMOVETAG, true); // edit task HashMap<Flag, String> argsToEdit = new HashMap<Flag, String>(); argsToEdit.put(nameOpt, "-n Meet Betty Green"); argsToEdit.put(dateTimeOpt, "-dt 20/09/2016 1800 to 21/09/2016 1800"); argsToEdit.put(priorityOpt, "-p h"); argsToEdit.put(addTagOpt, "-ta tag3"); argsToEdit.put(removeTagOpt, "-tr tag2"); Task taskToEdit = taskToAdd; Task editedTask = expectedAB.editTask(taskToEdit, argsToEdit); helper.addToModel(model, listToEdit); String inputCommand = "edit 1 -n Meet Betty Green -dt 20/09/2016 1800 " + "to 21/09/2016 1800 -p h -tr tag2 -ta tag3"; // execute command assertCommandBehavior(inputCommand, String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask), expectedAB, expectedAB.getTaskList()); } @Test public void execute_cd_incorrectArgsFormat_errorMessageShown() throws Exception { assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH); } @Test public void execute_cd_invalidFileType_errorMessageShown() throws Exception { assertCommandBehavior("cd invalidFileType", CdCommand.MESSAGE_INVALID_FILEPATH); } @Test public void execute_cd_success() throws Exception { String tempTestTarsFilePath = saveFolder.getRoot().getPath() + "TempTestTars.xml"; assertCommandBehavior("cd " + tempTestTarsFilePath, String.format(CdCommand.MESSAGE_SUCCESS, tempTestTarsFilePath)); } @Test public void execute_mark_allTaskAsDone() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task1 = helper.generateTaskWithName("task1"); Task task2 = helper.generateTaskWithName("task2"); List<Task> taskList = helper.generateTaskList(task1, task2); Tars expectedAB = new Tars(); helper.addToModel(model, taskList); Status done = new Status(true); task1.setStatus(done); task2.setStatus(done); expectedAB.addTask(task1); expectedAB.addTask(task2); assertCommandBehavior("mark -do 1 2", MarkCommand.MESSAGE_MARK_SUCCESS, expectedAB, expectedAB.getTaskList()); } @Test public void execute_mark_allTaskAsUndone() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task1 = helper.generateTaskWithName("task1"); Task task2 = helper.generateTaskWithName("task2"); Status done = new Status(true); task1.setStatus(done); task2.setStatus(done); List<Task> taskList = helper.generateTaskList(task1, task2); Tars expectedAB = new Tars(); helper.addToModel(model, taskList); Status undone = new Status(false); task1.setStatus(undone); task2.setStatus(undone); expectedAB.addTask(task1); expectedAB.addTask(task2); assertCommandBehavior("mark -ud 1 2", MarkCommand.MESSAGE_MARK_SUCCESS, expectedAB, expectedAB.getTaskList()); } /* * A method to undo any changes to the Tars File Path during tests */ public void undoChangeInTarsFilePath() throws IOException { ConfigUtil.saveConfig(originalConfig, configFilePath); } /** * A utility class to generate test data. */ class TestDataHelper { Task meetAdam() throws Exception { Name name = new Name("Meet Adam Brown"); DateTime dateTime = new DateTime("01/09/2016 1400", "01/09/2016 1500"); Priority priority = new Priority("m"); Status status = new Status(false); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("tag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, dateTime, priority, status, tags); } Task floatTask() throws Exception { Name name = new Name("Do homework"); DateTime dateTime = new DateTime("", ""); Priority priority = new Priority(""); Status status = new Status(false); UniqueTagList tags = new UniqueTagList(); return new Task(name, dateTime, priority, status, tags); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will have * the same state. Each unique seed will generate a unique Task object. * * @param seed * used to generate the task data field values */ Task generateTask(int seed) throws Exception { int seed2 = (seed + 1) % 31 + 1; // Generate 2nd seed for DateTime // value return new Task(new Name("Task " + seed), new DateTime(seed + "/01/2016 1400", seed2 + "/01/2016 2200"), new Priority("h"), new Status(false), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))); } /** Generates the correct add command based on the task given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add ").append(p.getName().toString()); if (p.getDateTime().toString().length() > 0) { cmd.append(" -dt ").append(p.getDateTime().toString()); } if (p.getPriority().toString().length() > 0) { cmd.append(" -p ").append(p.getPriority().toString()); } UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" -t ").append(t.tagName); } return cmd.toString(); } /** * Generates an Tars with auto-generated undone tasks. */ Tars generateTars(int numGenerated) throws Exception { Tars tars = new Tars(); addToTars(tars, numGenerated); return tars; } /** * Generates an Tars based on the list of Tasks given. */ Tars generateTars(List<Task> tasks) throws Exception { Tars tars = new Tars(); addToTars(tars, tasks); return tars; } /** * Adds auto-generated Task objects to the given Tars * * @param tars * The Tars to which the Tasks will be added */ void addToTars(Tars tars, int numGenerated) throws Exception { addToTars(tars, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given Tars */ void addToTars(Tars tars, List<Task> tasksToAdd) throws Exception { for (Task p : tasksToAdd) { tars.addTask(p); } } /** * Adds auto-generated Task objects to the given model * * @param model * The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p : tasksToAdd) { model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some * dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task(new Name(name), new DateTime("05/09/2016 1400", "06/09/2016 2200"), new Priority("h"), new Status(false), new UniqueTagList(new Tag("tag"))); } } }
package sample; import comlib.adk.team.tactics.straight.StraightPolice; import comlib.adk.util.route.RouteSearcher; import comlib.adk.util.route.sample.SampleRouteSearcher; import comlib.adk.util.target.BlockadeSelector; import comlib.adk.util.target.sample.SampleBlockadeSelector; import comlib.manager.MessageManager; public class SamplePolice extends StraightPolice { @Override public BlockadeSelector getBlockadeSelector() { return new SampleBlockadeSelector(this); } @Override public RouteSearcher getRouteSearcher() { return new SampleRouteSearcher(this); } @Override public void registerEvent(MessageManager manager) { } }
package com.example.arduinocontroller; import com.example.arduinocontroller.Constants; import com.example.arduinocontroller.SerialConnector; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ArduinoControllerActivity extends Activity implements View.OnClickListener { private Context mContext = null; private ActivityHandler mHandler = null; private SerialListener mListener = null; private SerialConnector mSerialConn = null; private TextView mTextLog = null; private TextView mTextInfo = null; private Button mButton1; private Button mButton2; private Button mButton3; private Button mButton4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // System mContext = getApplicationContext(); // Layouts setContentView(R.layout.activity_arduino_controller); mTextLog = (TextView) findViewById(R.id.text_serial); mTextLog.setMovementMethod(new ScrollingMovementMethod()); mTextInfo = (TextView) findViewById(R.id.text_info); mTextInfo.setMovementMethod(new ScrollingMovementMethod()); mButton1 = (Button) findViewById(R.id.button_send1); mButton1.setOnClickListener(this); mButton2 = (Button) findViewById(R.id.button_send2); mButton2.setOnClickListener(this); mButton3 = (Button) findViewById(R.id.button_send3); mButton3.setOnClickListener(this); mButton4 = (Button) findViewById(R.id.button_send4); mButton4.setOnClickListener(this); // Initialize mListener = new SerialListener(); mHandler = new ActivityHandler(); // Initialize Serial connector and starts Serial monitoring thread. mSerialConn = new SerialConnector(mContext, mListener, mHandler); mSerialConn.initialize(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public void onDestroy() { super.onDestroy(); mSerialConn.finalize(); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.button_send1: mSerialConn.sendCommand("b1"); break; case R.id.button_send2: mSerialConn.sendCommand("b2"); break; case R.id.button_send3: mSerialConn.sendCommand("b3"); break; case R.id.button_send4: mSerialConn.sendCommand("b4"); break; default: break; } } public class SerialListener { public void onReceive(int msg, int arg0, int arg1, String arg2, Object arg3) { switch(msg) { case Constants.MSG_DEVICD_INFO: mTextLog.append(arg2); break; case Constants.MSG_DEVICE_COUNT: mTextLog.append(Integer.toString(arg0) + " device(s) found \n"); break; case Constants.MSG_READ_DATA_COUNT: mTextLog.append(Integer.toString(arg0) + " buffer received \n"); break; case Constants.MSG_READ_DATA: if(arg3 != null) { mTextInfo.setText((String)arg3); mTextLog.append((String)arg3); mTextLog.append("\n"); } break; case Constants.MSG_SERIAL_ERROR: mTextLog.append(arg2); break; case Constants.MSG_FATAL_ERROR_FINISH_APP: finish(); break; } } } public class ActivityHandler extends Handler { @Override public void handleMessage(Message msg) { switch(msg.what) { case Constants.MSG_DEVICD_INFO: mTextLog.append((String)msg.obj); break; case Constants.MSG_DEVICE_COUNT: mTextLog.append(Integer.toString(msg.arg1) + " device(s) found \n"); break; case Constants.MSG_READ_DATA_COUNT: mTextLog.append(Integer.toString(msg.arg1) + " buffer received \n"); break; case Constants.MSG_READ_DATA: if(msg.obj != null) { mTextInfo.setText((String)msg.obj); mTextLog.append((String)msg.obj); mTextLog.append("\n"); } break; case Constants.MSG_SERIAL_ERROR: mTextLog.append((String)msg.obj); break; } } } }
package gov.sandia.cognition.algorithm; import gov.sandia.cognition.io.serialization.XStreamSerializationHandler; import gov.sandia.cognition.math.LentzMethod; import java.util.Random; import junit.framework.TestCase; /** * Unit tests for AnytimeAlgorithmWrapper * * @author krdixon */ public class AnytimeAlgorithmWrapperTest extends TestCase { /** * Test * @param testName name of test. */ public AnytimeAlgorithmWrapperTest( String testName) { super(testName); } /** * random */ public static Random random = new Random( 1 ); /** * wrapper */ public static class AAWrapper extends AnytimeAlgorithmWrapper<Double,LentzMethod> implements Runnable { /** * algorithm start */ public boolean algorithmStartedFlag = false; /** * algorithm end */ public boolean algorithmEndedFlag = false; /** * step start */ public boolean stepStartFlag = false; /** * step end */ public boolean stepEndedFlag = false; /** * Default */ public AAWrapper() { super( new LentzMethod() ); } /** * Constructor * @param d d */ public AAWrapper( boolean d ) { super(); } /** * Defaykt * @return */ public static AAWrapper defaultConstructor() { return new AAWrapper(false); } public Double getResult() { return this.getAlgorithm().getResult(); } public void run() { double a = random.nextDouble() + 1.0; double b = random.nextDouble(); this.getAlgorithm().initializeAlgorithm(b); while( this.getAlgorithm().getKeepGoing() ) { this.getAlgorithm().iterate(a,b); } } @Override public void algorithmStarted( IterativeAlgorithm algorithm) { super.algorithmStarted(algorithm); this.algorithmStartedFlag = true; } @Override public void algorithmEnded(IterativeAlgorithm algorithm) { super.algorithmEnded(algorithm); this.algorithmEndedFlag = true; } @Override public void stepEnded(IterativeAlgorithm algorithm) { super.stepEnded(algorithm); this.stepEndedFlag = true; } @Override public void stepStarted(IterativeAlgorithm algorithm) { super.stepStarted(algorithm); this.stepStartFlag = true; } } /** * Creates instance * @return instance */ public AAWrapper createInstance() { return new AAWrapper(); } /** * Tests constructors */ public void testConstructors() { System.out.println( "Constructors" ); AAWrapper instance = AAWrapper.defaultConstructor(); assertNull( instance.getAlgorithm() ); instance = new AAWrapper(); assertNotNull( instance.getAlgorithm() ); } /** * Tests clone */ public void testClone() { System.out.println( "Clone" ); AAWrapper instance = this.createInstance(); AAWrapper clone = (AAWrapper) instance.clone(); assertNotNull( clone ); assertNotSame( instance, clone ); assertNotNull( clone.getAlgorithm() ); assertNotSame( instance.getAlgorithm(), clone.getAlgorithm() ); } /** * Test of getMaxIterations method, of class AnytimeAlgorithmWrapper. */ public void testGetMaxIterations() { System.out.println("getMaxIterations"); AnytimeAlgorithmWrapper<?,?> instance = this.createInstance(); assertTrue( instance.getMaxIterations() > 0 ); assertEquals( instance.getAlgorithm().getMaxIterations(), instance.getMaxIterations() ); } /** * Test of setMaxIterations method, of class AnytimeAlgorithmWrapper. */ public void testSetMaxIterations() { System.out.println("setMaxIterations"); AnytimeAlgorithmWrapper<?,?> instance = this.createInstance(); int i = instance.getMaxIterations(); int i2 = i += random.nextInt(100) + 1; instance.setMaxIterations(i2); assertEquals( i2, instance.getMaxIterations() ); try { instance.setMaxIterations( 0 ); fail( "Max iterations must be > 0" ); } catch (Exception e) { System.out.println( "Good: " + e ); } } /** * Test of getAlgorithm method, of class AnytimeAlgorithmWrapper. */ public void testGetAlgorithm() { System.out.println("getAlgorithm"); AnytimeAlgorithmWrapper<?,?> instance = this.createInstance(); assertNotNull( instance.getAlgorithm() ); } /** * Test of setAlgorithm method, of class AnytimeAlgorithmWrapper. */ @SuppressWarnings("unchecked") public void testSetAlgorithm() { System.out.println("setAlgorithm"); AnytimeAlgorithmWrapper<Double,LentzMethod> instance = this.createInstance(); LentzMethod algorithm = instance.getAlgorithm(); assertNotNull( algorithm ); instance.setAlgorithm(null); assertNull( instance.getAlgorithm() ); instance.setAlgorithm(algorithm); assertSame( algorithm, instance.getAlgorithm() ); } /** * Test of stop method, of class AnytimeAlgorithmWrapper. */ @SuppressWarnings("unchecked") public void testStop() { System.out.println("stop"); AAWrapper instance = this.createInstance(); instance.getAlgorithm().initializeAlgorithm(random.nextDouble()); instance.getAlgorithm().iterate( random.nextDouble(), random.nextDouble() ); instance.stop(); try { instance.getAlgorithm().iterate( random.nextDouble(), random.nextDouble() ); fail( "Cannot iterate after stopping!" ); } catch (Exception e) { System.out.println( "Good: " + e ); } instance.setAlgorithm(null); instance.stop(); } /** * Test of getIteration method, of class AnytimeAlgorithmWrapper. */ public void testGetIteration() { System.out.println("getIteration"); AAWrapper instance = this.createInstance(); assertEquals( 0, instance.getIteration() ); instance.getAlgorithm().initializeAlgorithm(random.nextDouble()); instance.getAlgorithm().iterate( random.nextDouble(), random.nextDouble() ); assertEquals( 1, instance.getIteration() ); } /** * Test of isResultValid method, of class AnytimeAlgorithmWrapper. */ public void testIsResultValid() { System.out.println("isResultValid"); AnytimeAlgorithmWrapper<?,?> instance = this.createInstance(); assertFalse( instance.isResultValid() ); assertNull( instance.getResult() ); } /** * Algorithm Stuff */ public void testAlgorithmStuff() { System.out.println( "Algorithm Stuff" ); AAWrapper instance = this.createInstance(); assertFalse( instance.isResultValid() ); instance.run(); assertTrue( instance.isResultValid() ); assertTrue( instance.algorithmStartedFlag ); assertTrue( instance.algorithmEndedFlag ); assertTrue( instance.stepStartFlag ); assertTrue( instance.stepEndedFlag ); } /** * Tests the serialization code regarding readResolve. * * @throws java.lang.Exception */ public void testReadResolve() throws Exception { AAWrapper instance = this.createInstance(); assertTrue(instance.getAlgorithm().getListeners().contains(instance)); XStreamSerializationHandler handler = XStreamSerializationHandler.getDefault(); String serialized = handler.convertToString(instance); System.out.println(serialized); AAWrapper deserialized = (AAWrapper) handler.convertFromString( serialized); // The main part of read-resolve is to make sure that the wrapper is // connected to the algorithm after deserialization. assertTrue(deserialized.getAlgorithm().getListeners().contains( deserialized)); deserialized.run(); assertTrue(deserialized.algorithmStartedFlag); assertTrue(deserialized.algorithmEndedFlag); assertTrue(deserialized.stepStartFlag); assertTrue(deserialized.stepEndedFlag); } }
package eu.qualimaster.coordination; import java.io.File; import java.io.IOException; 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 org.apache.commons.io.FileUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import eu.qualimaster.common.signal.AbstractTopologyExecutorSignal; import eu.qualimaster.common.signal.AlgorithmChangeSignal; import eu.qualimaster.common.signal.LoadSheddingSignal; import eu.qualimaster.common.signal.MonitoringChangeSignal; import eu.qualimaster.common.signal.ParameterChange; import eu.qualimaster.common.signal.ParameterChangeSignal; import eu.qualimaster.common.signal.ReplaySignal; import eu.qualimaster.common.signal.ShutdownSignal; import eu.qualimaster.common.signal.SignalException; import eu.qualimaster.common.signal.SignalMechanism; import eu.qualimaster.coordination.INameMapping.Algorithm; import eu.qualimaster.coordination.INameMapping.Component; import eu.qualimaster.coordination.INameMapping.ISubPipeline; import eu.qualimaster.coordination.PipelineCache.PipelineElementCache; import eu.qualimaster.coordination.RepositoryConnector.Models; import eu.qualimaster.coordination.StormUtils.TopologyTestInfo; import eu.qualimaster.coordination.commands.AlgorithmChangeCommand; import eu.qualimaster.coordination.commands.CommandSequence; import eu.qualimaster.coordination.commands.CommandSet; import eu.qualimaster.coordination.commands.CoordinationCommand; import eu.qualimaster.coordination.commands.CoordinationExecutionResult; import eu.qualimaster.coordination.commands.LoadSheddingCommand; import eu.qualimaster.coordination.commands.MonitoringChangeCommand; import eu.qualimaster.coordination.commands.ParallelismChangeCommand; import eu.qualimaster.coordination.commands.ParameterChangeCommand; import eu.qualimaster.coordination.commands.PipelineCommand; import eu.qualimaster.coordination.commands.PipelineCommand.Status; import eu.qualimaster.coordination.events.CoordinationCommandExecutionEvent; import eu.qualimaster.coordination.commands.ProfileAlgorithmCommand; import eu.qualimaster.coordination.commands.ReplayCommand; import eu.qualimaster.coordination.commands.ScheduleWavefrontAdaptationCommand; import eu.qualimaster.coordination.commands.ShutdownCommand; import eu.qualimaster.coordination.commands.UpdateCommand; import eu.qualimaster.coordination.shutdown.Shutdown; import eu.qualimaster.dataManagement.DataManager; import eu.qualimaster.easy.extension.internal.AlgorithmProfileHelper; import eu.qualimaster.easy.extension.internal.AlgorithmProfileHelper.ProfileData; import eu.qualimaster.easy.extension.internal.QmProjectDescriptor; import eu.qualimaster.events.EventManager; import eu.qualimaster.infrastructure.PipelineLifecycleEvent; import eu.qualimaster.infrastructure.PipelineOptions; import eu.qualimaster.monitoring.events.ChangeMonitoringEvent; import net.ssehub.easy.basics.modelManagement.ModelInitializer; import net.ssehub.easy.basics.modelManagement.ModelManagementException; import net.ssehub.easy.basics.progress.ProgressObserver; import net.ssehub.easy.instantiation.core.model.common.VilException; import static eu.qualimaster.coordination.CoordinationUtils.getNamespace; /** * Visits the commands for execution. Please note that when starting the execution of a single command, * the command must be placed on the {@link #commandStack} and at the end of the execution (no exception must * be thrown) {@link #writeCoordinationLog(CoordinationCommand, CoordinationExecutionResult)} must be * called which pops from the stack and performs the logging. * * @author Holger Eichelberger */ class CoordinationCommandExecutionVisitor extends AbstractCoordinationCommandExecutionVisitor { private static final Set<Class<? extends CoordinationCommand>> DEFER_SUCCESSFUL_EXECUTION = new HashSet<Class<? extends CoordinationCommand>>(); private long timestamp = System.currentTimeMillis(); private ActiveCommands activeCommands = null; static { // later, all command shall be deferred and report about the actual completion DEFER_SUCCESSFUL_EXECUTION.add(PipelineCommand.class); } /** * Creates a command execution visitor. * * @param tracer a tracer for obtaining information about the execution */ CoordinationCommandExecutionVisitor(IExecutionTracer tracer) { super(tracer); } /** * Sets the top-level command of this execution. * * @param command the command * @return the active commands object */ ActiveCommands setTopLevelCommand(CoordinationCommand command) { activeCommands = new ActiveCommands(command); return activeCommands; } /** * Returns the actual message id. * * @return the actual message id */ private String getCauseMessageId() { return null == activeCommands ? "" : activeCommands.getCauseMessageId(); } /** * Handles sending a (storm commons) signal. * * @param command the command causing the signal * @param signal the signal * @return whether the execution failed (instance) or not (<b>null</b>) */ private static CoordinationExecutionResult send(CoordinationCommand command, AbstractTopologyExecutorSignal signal) { CoordinationExecutionResult failing = null; try { if (!CoordinationManager.isTestingMode()) { getLogger().info("Sending signal " + signal); signal.sendSignal(); } } catch (SignalException e) { failing = new CoordinationExecutionResult(command, e.getMessage(), CoordinationExecutionCode.SIGNAL_SENDING_ERROR); } return failing; } @Override public CoordinationExecutionResult visitAlgorithmChangeCommand(AlgorithmChangeCommand command) { return handleAlgorithmChange(command, null); } @Override protected CoordinationExecutionResult handleAlgorithmChange(AlgorithmChangeCommand command, List<ParameterChange> parameters) { CoordinationExecutionResult result; String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); ISubPipeline subPip = mapping.getSubPipelineByAlgorithmName(command.getAlgorithm()); if (null != subPip) { CoordinationManager.deferCommand(subPip.getName(), PipelineLifecycleEvent.Status.STARTED, new AlgorithmChangeAction(command, parameters, getTracer())); PipelineCommand cmd = new PipelineCommand(subPip.getName(), PipelineCommand.Status.START, getSubPipelineOptions(pipelineName, command.getOptions())); result = handlePipelineStart(cmd); } else { result = handleAlgorithmChangeImpl(command, parameters); } return result; } /** * Returns the sub pipeline options. * * @param mainPipeline the main pipeline * @param commandOptions the options introduced by the command * @return the options for the sub-pipeline marked as sub-pipeline */ private PipelineOptions getSubPipelineOptions(String mainPipeline, PipelineOptions commandOptions) { PipelineOptions opts = CoordinationManager.getPipelineOptions(mainPipeline); if (null == opts) { opts = new PipelineOptions(); // shall not occur } else { opts = new PipelineOptions(opts); // clone } if (null != commandOptions) { // take into account decisions done by the adaptation for algorithm change opts.merge(commandOptions); } opts.markAsSubPipeline(mainPipeline); return opts; } /** * Handles an algorithm change command with optional parameters. This method may be an entry point for deferred * actions. * * @param command the command * @param parameters explicit parameters (may be <b>null</b> than only the cached ones will be used) * @return the coordination execution result */ CoordinationExecutionResult handleAlgorithmChangeImpl(AlgorithmChangeCommand command, List<ParameterChange> parameters) { CoordinationExecutionResult failing = null; startingCommand(command); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); Component receiver = CoordinationUtils.getReceiverComponent( mapping.getPipelineNodeComponent(command.getPipelineElement())); if (null == receiver) { String message = "no receiver for changing the algorithm on " + command.getPipeline() + "/" + command.getPipelineElement(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.SIGNAL_SENDING_ERROR); } else { PipelineElementCache cache = PipelineCache.getCache(command); if (null == parameters) { parameters = cache.parameters(); } String algorithm = command.getAlgorithm(); Algorithm alg = mapping.getAlgorithm(algorithm); if (null != alg) { algorithm = alg.getName(); // the implementation name } AlgorithmChangeSignal signal = new AlgorithmChangeSignal(getNamespace(mapping), receiver.getName(), algorithm, parameters, getCauseMessageId()); signal.setParameters(command.getParameters()); send(command, signal); cache.setAlgorithm(command.getAlgorithm(), parameters); } if (null != getTracer()) { getTracer().executedAlgorithmChangeCommand(command, failing); } return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitParameterChangeCommand(ParameterChangeCommand<?> command) { return handleParameterChange(command, null); } @Override protected CoordinationExecutionResult handleParameterChange(ParameterChangeCommand<?> command, List<ParameterChange> huckup) { CoordinationExecutionResult failing = null; startingCommand(command); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); Component receiver = CoordinationUtils.getReceiverComponent(CoordinationUtils.getParameterReceiverComponent( mapping, command.getPipelineElement(), command.getParameter())); if (null == receiver) { String message = "no receiver for changing the parameter on " + command.getPipeline() + "/" + command.getPipelineElement(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.SIGNAL_SENDING_ERROR); } else { List<ParameterChange> changes = new ArrayList<ParameterChange>(); changes.add(new ParameterChange(command.getParameter(), command.getValue())); if (null != huckup) { changes.addAll(huckup); } ParameterChangeSignal signal = new ParameterChangeSignal(getNamespace(mapping), receiver.getName(), changes, getCauseMessageId()); send(command, signal); PipelineCache.getCache(command).setParameters(changes, false); } if (null != getTracer()) { getTracer().executedParameterChangeCommand(command, failing); } return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitCommandSequence(CommandSequence command) { CoordinationExecutionResult failed = null; startingCommand(command); CommandSequenceGroupingVisitor gVisitor = new CommandSequenceGroupingVisitor(); gVisitor.setExecutor(this); for (int c = 0; null == failed && c < command.getCommandCount(); c++) { failed = command.getCommand(c).accept(gVisitor); } if (null == failed) { failed = gVisitor.flush(); } if (null != getTracer()) { getTracer().executedCommandSequence(command, failed); } return writeCoordinationLog(command, failed); } @Override public CoordinationExecutionResult visitCommandSet(CommandSet command) { CoordinationExecutionResult failed = null; startingCommand(command); CommandSetGroupingVisitor gVisitor = new CommandSetGroupingVisitor(); for (int c = 0; c < command.getCommandCount(); c++) { command.getCommand(c).accept(gVisitor); } gVisitor.setExecutor(this); for (int c = 0; null == failed && c < command.getCommandCount(); c++) { failed = command.getCommand(c).accept(gVisitor); } if (null != getTracer()) { getTracer().executedCommandSet(command, failed); } return writeCoordinationLog(command, failed); } @Override public CoordinationExecutionResult visitPipelineCommand(PipelineCommand command) { CoordinationExecutionResult failing = null; boolean deferred = false; startingCommand(command); Status status = command.getStatus(); boolean knownCommand = false; if (null != status) { knownCommand = true; String pipelineName = command.getPipeline(); switch (status) { case START: if (null == pipelineName) { failing = new CoordinationExecutionResult(command, "illegal pipeline name: null", CoordinationExecutionCode.STARTING_PIPELINE); } else { if (CoordinationManager.isStartupPending(pipelineName)) { CoordinationManager.removePendingStartup(pipelineName); failing = handlePipelineStart(command); } else { getLogger().info("Deferring pipeline start command for " + pipelineName); CoordinationManager.deferStartup(command); EventManager.handle(new PipelineLifecycleEvent(pipelineName, PipelineLifecycleEvent.Status.CHECKING, command.getOptions(), command)); deferred = true; } } break; case CONNECT: DataManager.connectAll(command.getPipeline()); break; case DISCONNECT: DataManager.disconnectAll(command.getPipeline()); break; case STOP: failing = handlePipelineStop(command, true); break; default: knownCommand = false; break; } } if (!knownCommand) { String message = "unknown pipeline command state: " + command.getStatus(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.UNKNOWN_COMMAND); } if (!deferred) { if (null != getTracer()) { getTracer().executedPipelineCommand(command, failing); } failing = writeCoordinationLog(command, failing); } return failing; } /** * Handles starting a pipeline. * * @param command the pipeline start command * @return the pipeline execution result */ private CoordinationExecutionResult handlePipelineStart(PipelineCommand command) { CoordinationExecutionResult failing = null; CoordinationManager.registerPipelineOptions(command.getPipeline(), command.getOptions()); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); getLogger().info("Processing pipeline start command for " + pipelineName + " with options " + command.getOptions()); try { String absPath = CoordinationUtils.loadMapping(pipelineName); doPipelineStart(mapping, absPath, command.getOptions(), command); } catch (IOException e) { // implies file not found! String message = "while starting pipeline '" + command.getPipeline() + "': " + e.getMessage(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.STARTING_PIPELINE); } return failing; } /** * Actually performs the pipeline start. * * @param mapping the name mapping instance * @param jarPath the absolute path to the pipeline Jar * @param options the pipeline options * @param command the causing command (may be <b>null</b>) * @throws IOException in case that stopping fails */ static void doPipelineStart(INameMapping mapping, String jarPath, PipelineOptions options, CoordinationCommand command) throws IOException { String pipelineName = mapping.getPipelineName(); try { // just in case that the pipeline was killed manually SignalMechanism.getPortManager().clearPortAssignments(pipelineName); } catch (SignalException e) { getLogger().error(e.getMessage()); } PipelineCache.getCache(pipelineName); // prepare the cache if (!CoordinationManager.isTestingMode()) { StormUtils.submitTopology(CoordinationConfiguration.getNimbus(), mapping, jarPath, options); // cache curator, takes a while, pass "virtual" namespace for namespace state SignalMechanism.prepareMechanism(getNamespace(mapping)); } EventManager.handle(new PipelineLifecycleEvent(pipelineName, PipelineLifecycleEvent.Status.STARTING, options, command)); // if monitoring detects, that all families are initialized, it switches to INITIALIZED causing the // DataManger to connect the sources } /** * Handles stopping a pipeline. * * @param command the pipeline start command * @param top is this a top-level or a sub-pipeline call * @return the pipeline execution result */ private CoordinationExecutionResult handlePipelineStop(PipelineCommand command, boolean top) { CoordinationExecutionResult failing = null; String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); String pipText = top ? "pipeline" : "sub-pipeline"; getLogger().info("Processing " + pipText + " stop command for " + pipelineName + " with options " + command.getOptions()); try { doPipelineStop(mapping, command.getOptions(), command); CoordinationManager.unregisterNameMapping(mapping); SignalMechanism.getPortManager().clearPortAssignments(pipelineName); } catch (IOException e) { String message = "while stopping " + pipText + " '" + command.getPipeline() + "': " + e.getMessage(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.STOPPING_PIPELINE); } catch (SignalException e) { getLogger().error(e.getMessage()); } for (ISubPipeline sp : mapping.getSubPipelines()) { handlePipelineStop(new PipelineCommand(sp.getName(), command.getStatus(), command.getOptions()), false); } return failing; } /** * Actually performs the pipeline stop. This method does not unregister the name mapping! * * @param mapping the name mapping instance * @param options the pipeline options * @param command the causing command (may be <b>null</b>) * @throws IOException in case that stopping fails */ static void doPipelineStop(INameMapping mapping, PipelineOptions options, CoordinationCommand command) throws IOException { String pipelineName = mapping.getPipelineName(); EventManager.handle(new PipelineLifecycleEvent(pipelineName, PipelineLifecycleEvent.Status.STOPPING, command)); for (Component c : mapping.getComponents()) { ShutdownSignal signal = new ShutdownSignal(getNamespace(mapping), c.getName()); send(command, signal); // ignore failing } Utils.sleep(CoordinationConfiguration.getShutdownSignalWaitTime()); SignalMechanism.releaseMechanism(getNamespace(mapping)); if (!CoordinationManager.isTestingMode()) { // TODO stop multiple physical sub-topologies StormUtils.killTopology(CoordinationConfiguration.getNimbus(), pipelineName, CoordinationConfiguration.getStormCmdWaitingTime(), options, true); // TODO unload MaxFiles (currently assuming exclusive DFE use) } PipelineCache.removeCache(pipelineName); EventManager.handle(new PipelineLifecycleEvent(pipelineName, PipelineLifecycleEvent.Status.STOPPED, command)); } @Override public CoordinationExecutionResult visitScheduleWavefrontAdaptationCommand( ScheduleWavefrontAdaptationCommand command) { startingCommand(command); // TODO to be done later, writeCoordinationLog if (null != getTracer()) { getTracer().executedScheduleWavefrontAdaptationCommand(command, null); } return writeCoordinationLog(command, new CoordinationExecutionResult(command, "not yet implemented", CoordinationExecutionCode.NOT_IMPLEMENTED)); } @Override public CoordinationExecutionResult visitMonitoringChangeCommand(MonitoringChangeCommand command) { startingCommand(command); // just forward to the monitoring layer String pipelineName = command.getPipeline(); if (null != pipelineName && null != command.getPipelineElement()) { INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); Component receiver = CoordinationUtils.getReceiverComponent( mapping.getPipelineNodeComponent(command.getPipelineElement())); if (null != receiver) { MonitoringChangeSignal signal = new MonitoringChangeSignal(getNamespace(mapping), receiver.getName(), command.getFrequencies(), command.getObservables(), getCauseMessageId()); send(command, signal); } } EventManager.handle(new ChangeMonitoringEvent(command.getPipeline(), command.getPipelineElement(), command.getFrequencies(), command.getObservables(), command)); if (null != getTracer()) { getTracer().executedMonitoringChangeCommand(command, null); } return writeCoordinationLog(command, null); } /** * Pops the actual command from the stack and in case of a failure, writes the message to logging * and the whole information to the coordination log if on top level. * * @param command the current command being executed * @param failing the failing command (may be <b>null</b> if no execution failure) * @return <code>failing</code> */ protected CoordinationExecutionResult writeCoordinationLog(CoordinationCommand command, CoordinationExecutionResult failing) { endingCommand(command); if (null != failing) { getLogger().error("enactment failed: " + failing.getMessage()); } if (isProcessingCommands()) { CoordinationCommand cmd; String message; int code; boolean sendEvent; if (null == failing) { cmd = command; message = ""; code = CoordinationExecutionCode.SUCCESSFUL; sendEvent = !DEFER_SUCCESSFUL_EXECUTION.contains(command.getClass()); } else { cmd = failing.getCommand(); message = failing.getMessage(); code = failing.getCode(); sendEvent = true; // immediate in failure case } // TODO this shall go to the data management layer String text = "CoordinationLog: " + timestamp + " " + cmd.getClass().getName() + " " + message + " " + code; System.out.println(text); if (null != getTracer()) { getTracer().logEntryWritten(text); } if (sendEvent) { EventManager.handle(new CoordinationCommandExecutionEvent(command, cmd, code, message)); } } return failing; } @Override public CoordinationExecutionResult visitParallelismChangeCommand(ParallelismChangeCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); String errorMsg = null; if (!mapping.isIdentity()) { // testing, unknown pipeline if (null != command.getIncrementalChanges()) { Map<String, ParallelismChangeRequest> changeMapping = mapChanges(mapping, command.getIncrementalChanges()); String cmd = "Changing parallism of " + pipelineName + ":"; for (Map.Entry<String, ParallelismChangeRequest> entry : changeMapping.entrySet()) { cmd += " " + entry.getKey() + "=" + entry.getValue(); } getLogger().info(cmd); try { StormUtils.changeParallelism(pipelineName, changeMapping); } catch (IOException e) { errorMsg = "While changing pipeline parallelism of '" + pipelineName + "': " + e.getMessage(); } } else if (null != command.getExecutors()) { Map<String, Integer> execMapping = mapChanges(mapping, command.getExecutors()); String cmd = "Rebalancing " + pipelineName + " -n " + command.getNumberOfWorkers(); for (Map.Entry<String, Integer> entry : execMapping.entrySet()) { cmd += " -e " + entry.getValue() + "=" + entry.getValue(); } getLogger().info(cmd); try { StormUtils.rebalance(CoordinationConfiguration.getNimbus(), pipelineName, command.getNumberOfWorkers(), execMapping, CoordinationConfiguration.getStormCmdWaitingTime()); } catch (IOException e) { errorMsg = "while rebalancing pipeline '" + pipelineName + "': " + e.getMessage(); } } // no changes given, no failure } // ignore for testing, no failure if (null != errorMsg) { failing = new CoordinationExecutionResult(command, errorMsg, CoordinationExecutionCode.CHANGING_PARALLELISM); } if (null != getTracer()) { getTracer().executedParallelismChangeCommand(command, failing); } return writeCoordinationLog(command, failing); } /** * Maps pipeline changes from pipeline names to executor / component names. * * @param <T> the type of the change * @param mapping the name mapping to be applied * @param changes the changes assigned to pipeline names * @return the mapped changes assigned to executor / component names */ private static <T> Map<String, T> mapChanges(INameMapping mapping, Map<String, T> changes) { Map<String, T> result = new HashMap<String, T>(); for (Map.Entry<String, T> entry : changes.entrySet()) { Component comp = mapping.getPipelineNodeComponent(entry.getKey()); if (null != comp) { result.put(comp.getName(), entry.getValue()); } } return result; } /** * Returns the logger for this class. * * @return the logger */ private static Logger getLogger() { return LogManager.getLogger(CoordinationCommandExecutionVisitor.class); } @Override public CoordinationExecutionResult visitProfileAlgorithmCommand(ProfileAlgorithmCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); Models models = RepositoryConnector.getModels(RepositoryConnector.getPhaseWithVil()); if (null == models) { failing = new CoordinationExecutionResult(command, "Configuration model is not available " + "- see messages above", CoordinationExecutionCode.CHANGING_PARALLELISM); } else { models.startUsing(); //models.reloadIvml(); models.reloadVil(); net.ssehub.easy.varModel.confModel.Configuration cfg = models.getConfiguration(); File tmp = null; try { String pipelineName; tmp = new File(FileUtils.getTempDirectory(), "qmDebugProfile"); org.apache.commons.io.FileUtils.deleteDirectory(tmp); tmp.mkdirs(); if (StormUtils.inTesting()) { Set<String> testing = StormUtils.getTestingTopologyNames(); Object[] testingTmp = testing.toArray(); if (testingTmp.length > 0) { pipelineName = testingTmp[0].toString(); TopologyTestInfo info = StormUtils.getTestInfo(pipelineName); FileUtils.copyDirectory(info.getBaseFolder(), tmp); } else { pipelineName = "TestPip"; // fallback - fails as no VIL present } } else { pipelineName = "TestPip" + System.currentTimeMillis(); FileUtils.copyDirectory(RepositoryConnector.getCurrentModelPath().toFile(), tmp); } ModelInitializer.addLocation(tmp, ProgressObserver.NO_OBSERVER); ProfileData data; try { QmProjectDescriptor source = new QmProjectDescriptor(tmp); data = AlgorithmProfileHelper.createProfilePipeline(cfg, pipelineName, command.getFamily(), command.getAlgorithm(), source); } catch (ModelManagementException e) { data = null; if (StormUtils.inTesting()) { TopologyTestInfo tInfo = StormUtils.getTestInfo(); data = null != tInfo ? tInfo.getProfileData() : null; } if (null == data) { throw e; } } ProfileControl control = new ProfileControl(cfg, command, data); control.startNext(); } catch (ModelManagementException | VilException | IOException e) { failing = new CoordinationExecutionResult(command, e.getMessage(), CoordinationExecutionCode.PROFILING); } if (null != tmp) { try { ModelInitializer.removeLocation(tmp, ProgressObserver.NO_OBSERVER); if (CoordinationConfiguration.deleteProfilingPipelines()) { FileUtils.deleteQuietly(tmp); } } catch (ModelManagementException e) { getLogger().error("While clearning up profiling creation folders: " + e.getMessage()); } } models.reloadVil(); models.endUsing(); } return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitShutdownCommand(ShutdownCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); Set<String> pips; do { // as stopping sub-pipelines affects getRegisteredPipelines, do it rather carefully pips = CoordinationManager.getRegisteredPipelines(); if (!pips.isEmpty()) { // ignore result for now handlePipelineStop(new PipelineCommand(pips.iterator().next(), PipelineCommand.Status.STOP), true); } } while (!pips.isEmpty()); Shutdown.shutdown(command); return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitUpdateCommand(UpdateCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); RepositoryConnector.updateModels(); return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitReplayCommand(ReplayCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); Component receiver = CoordinationUtils.getReceiverComponent( mapping.getPipelineNodeComponent(command.getPipelineElement())); if (null == receiver) { String message = "no receiver for sending replay command on " + command.getPipeline() + "/" + command.getPipelineElement(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.SIGNAL_SENDING_ERROR); } else { ReplaySignal signal = new ReplaySignal(getNamespace(mapping), receiver.getName(), command.getStartReplay(), command.getTicket(), getCauseMessageId()); if (command.getStartReplay()) { signal.setReplayStartInfo(command.getStart(), command.getEnd(), command.getSpeed(), command.getQuery()); } send(command, signal); } if (null != getTracer()) { getTracer().executedReplayCommand(command, failing); } return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitLoadScheddingCommand(LoadSheddingCommand command) { CoordinationExecutionResult failing = null; startingCommand(command); String pipelineName = command.getPipeline(); INameMapping mapping = CoordinationManager.getNameMapping(pipelineName); Component receiver = CoordinationUtils.getReceiverComponent( mapping.getPipelineNodeComponent(command.getPipelineElement())); if (null == receiver) { String message = "no receiver for sending replay command on " + command.getPipeline() + "/" + command.getPipelineElement(); failing = new CoordinationExecutionResult(command, message, CoordinationExecutionCode.SIGNAL_SENDING_ERROR); } else { LoadSheddingSignal signal = new LoadSheddingSignal(getNamespace(mapping), receiver.getName(), command.getShedder(), command.parameters(), getCauseMessageId()); send(command, signal); } if (null != getTracer()) { getTracer().executedLoadScheddingCommand(command, failing); } return writeCoordinationLog(command, failing); } @Override public CoordinationExecutionResult visitCloudExecutionCommand(CoordinationCommand command) { return null; } }
package com.antew.redditinpictures.library.service; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import com.antew.redditinpictures.library.logging.Log; import com.antew.redditinpictures.library.provider.RedditProvider; import com.antew.redditinpictures.library.reddit.MySubreddits; import com.antew.redditinpictures.library.reddit.RedditApi; import com.antew.redditinpictures.library.reddit.RedditApi.PostData; import com.antew.redditinpictures.library.reddit.RedditApiManager; import com.antew.redditinpictures.library.reddit.RedditLoginResponse; import com.antew.redditinpictures.library.reddit.RedditUrl; import com.antew.redditinpictures.library.reddit.RedditUrl.Age; import com.antew.redditinpictures.library.reddit.RedditUrl.Category; import com.antew.redditinpictures.library.reddit.SubscribeAction; import com.antew.redditinpictures.library.reddit.Vote; import com.antew.redditinpictures.library.utils.Consts; import com.antew.redditinpictures.sqlite.RedditContract; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; public class RedditService extends RESTService { private static final String TAG = RedditService.class.getName(); public static final String USER_AGENT = "Reddit In Pictures Android by /u/antew"; private static final String REDDIT_LOGIN_URL = "https://ssl.reddit.com/api/login/"; private static final String REDDIT_SUBSCRIBE_URL = "http: private static final String REDDIT_VOTE_URL = "http: private static final String REDDIT_ABOUT_URL = "http: public static final String REDDIT_SESSION = "reddit_session"; private static final String REDDIT_MY_SUBREDDITS_URL = "http: public static final String COMPACT_URL = "/.compact"; public static final String REDDIT_BASE_URL = "http: public interface RequestTypes { int LOGIN = 100; int POSTS = 110; int LOGOUT = 120; int VOTE = 130; int MY_SUBREDDITS = 140; int SUBSCRIBE = 150; int ABOUT_SUBREDDIT = 160; } public RedditService() { super(); } @Override protected void onHandleIntent(Intent intent) { super.onHandleIntent(intent); } @Override public void onRequestComplete(Intent result) { super.onRequestComplete(result); Bundle args = result.getBundleExtra(EXTRA_BUNDLE); int requestCode = args.getInt(EXTRA_REQUEST_CODE); int statusCode = args.getInt(EXTRA_STATUS_CODE); boolean replaceAll = args.getBoolean(EXTRA_REPLACE_ALL); String json = args.getString(REST_RESULT); if (statusCode != 200 || json == null) { return; } Gson gson = new Gson(); switch (requestCode) { case RequestTypes.POSTS: try { // Each time we want to remove the old before/after/modhash rows from the Reddit data int redditRowsDeleted = getContentResolver().delete(RedditContract.RedditData.CONTENT_URI, null, null); Log.i(TAG, "Deleted " + redditRowsDeleted + " reddit rows"); RedditApi redditApi = RedditApi.getGson().fromJson(json, RedditApi.class); List<PostData> mEntries = RedditApiManager.filterPosts(redditApi, true); ContentValues[] operations = RedditProvider.contentValuesFromPostData(mEntries); ContentValues redditValues = RedditProvider.contentValuesFromRedditApi(redditApi); // Add the new Reddit data Uri newData = getContentResolver().insert(RedditContract.RedditData.CONTENT_URI, redditValues); Log.i(TAG, "Inserted reddit data " + newData.toString()); // If we're loading a new subreddit remove all existing rows first if (replaceAll) { int rowsDeleted = getContentResolver().delete(RedditContract.Posts.CONTENT_URI, null, null); Log.i(TAG, "Deleted " + rowsDeleted + " posts"); } int rowsInserted = getContentResolver().bulkInsert(RedditContract.Posts.CONTENT_URI, operations); Log.i(TAG, "Inserted " + rowsInserted + " rows"); } catch (JsonSyntaxException e) { Log.e(TAG, "onReceiveResult - JsonSyntaxException while parsing json!", e); return; } catch (IllegalStateException e) { Log.e(TAG, "onReceiveResult - IllegalStateException while parsing json!", e); return; } break; case RequestTypes.LOGIN: Log.i(TAG, "login request finished! = " + json); RedditLoginResponse mRedditLoginResponse = new Gson().fromJson(json, RedditLoginResponse.class); break; case RequestTypes.MY_SUBREDDITS: Log.i(TAG, "MySubreddits complete! = " + json); MySubreddits mySubreddits = gson.fromJson(json, MySubreddits.class); break; case RequestTypes.VOTE: Log.i(TAG, "Got back from vote! = " + json); break; case RequestTypes.ABOUT_SUBREDDIT: Log.i(TAG, "Got back subreddit about! = " + json); break; case RequestTypes.SUBSCRIBE: Log.i(TAG, "Got back from subscribe! = " + json); break; } } private static Intent getIntentBasics(Intent intent) { intent.putExtra(EXTRA_USER_AGENT, USER_AGENT); if (RedditApiManager.isLoggedIn()) intent.putExtra(EXTRA_COOKIE, REDDIT_SESSION + "=" + RedditApiManager.getLoginCookie()); return intent; } public static Intent getPostIntent(Context context, String subreddit, Age age, Category category, String after, boolean replaceAll) { if (subreddit == null) subreddit = RedditUrl.REDDIT_FRONTPAGE; if (age == null) age = Age.TODAY; if (category == null) category = Category.HOT; //@formatter:off RedditUrl url = new RedditUrl.Builder(subreddit) .age(age) .category(category) .count(Consts.POSTS_TO_FETCH) .after(after) .build(); //@formatter:on return getPostIntent(context, url.getUrl(), replaceAll); } public static Intent getPostIntent(Context context, String url, boolean replaceAll) { Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.putExtra(RedditService.EXTRA_REQUEST_CODE, RequestTypes.POSTS); intent.putExtra(RedditService.EXTRA_REPLACE_ALL, replaceAll); intent.setData(Uri.parse(url)); return intent; } public static Intent getVoteIntent(Context context, String id, String subreddit, Vote vote) { Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.setData(Uri.parse(REDDIT_VOTE_URL)); intent.putExtra(EXTRA_HTTP_VERB, POST); intent.putExtra(RedditService.EXTRA_REQUEST_CODE, RequestTypes.VOTE); Bundle bundle = new Bundle(); bundle.putString("id", id); bundle.putInt("dir", vote.getVote()); bundle.putString("r", subreddit); bundle.putString("uh", RedditApiManager.getModHash()); intent.putExtra(EXTRA_PARAMS, bundle); return intent; } public static Intent getLoginIntent(Context context, String username, String password) { String url = REDDIT_LOGIN_URL + username; Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.setData(Uri.parse(url)); intent.putExtra(RedditService.EXTRA_REQUEST_CODE, RequestTypes.LOGIN); intent.putExtra(EXTRA_HTTP_VERB, POST); Bundle params = new Bundle(); params.putString("api_type", "json"); params.putString("user", username); params.putString("passwd", password); intent.putExtra(EXTRA_PARAMS, params); return intent; } public static Intent getMySubredditsIntent(Context context) { Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.setData(Uri.parse(REDDIT_MY_SUBREDDITS_URL)); intent.putExtra(RedditService.EXTRA_REQUEST_CODE, RequestTypes.MY_SUBREDDITS); intent.putExtra(EXTRA_HTTP_VERB, GET); return intent; } public static Intent getSubscribeIntent(Context context, String name, SubscribeAction action) { Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.setData(Uri.parse(REDDIT_SUBSCRIBE_URL)); intent.putExtra("action", action.getAction()); intent.putExtra("sr", name); intent.putExtra("uh", RedditApiManager.getModHash()); return intent; } public static Intent getAboutIntent(Context context, String subreddit) { Intent intent = new Intent(context, RedditService.class); intent = getIntentBasics(intent); intent.setData(Uri.parse(String.format(REDDIT_ABOUT_URL, subreddit))); return intent; } }
package eu.modelwriter.marker.ui.internal; import java.awt.Frame; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.swing.JMenuItem; import javax.swing.JPanel; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.MultiPageEditorPart; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4.Util; import edu.mit.csail.sdg.alloy4graph.GraphViewer; import edu.mit.csail.sdg.alloy4viz.AlloyAtom; import edu.mit.csail.sdg.alloy4viz.AlloyInstance; import edu.mit.csail.sdg.alloy4viz.MagicColor; import edu.mit.csail.sdg.alloy4viz.MagicLayout; import edu.mit.csail.sdg.alloy4viz.StaticInstanceReader; import edu.mit.csail.sdg.alloy4viz.VizGraphPanel; import edu.mit.csail.sdg.alloy4viz.VizState; import eu.modelwriter.configuration.alloy.AlloyParserForMetamodel; import eu.modelwriter.configuration.internal.AlloyUtilities; import eu.modelwriter.marker.internal.MarkUtilities; import eu.modelwriter.marker.internal.MarkerFactory; import eu.modelwriter.marker.ui.internal.views.Visualization; public class MetaModelEditor extends MultiPageEditorPart { public static final String ID = "eu.modelwriter.marker.ui.views.metamodelview"; private static VizState myState = null; private static VizGraphPanel graph; private static Frame frame; private static File file = null; public static Object rightClickedAnnotation; static String xmlFileName = null; static Composite modelEditor; private TextEditor textEditor; private void addDropListener() { final int acceptableOps = DnDConstants.ACTION_COPY; @SuppressWarnings("unused") final DropTarget dropTarget = new DropTarget(MetaModelEditor.graph.alloyGetViewer(), acceptableOps, new DropTargetListener() { ISelection selection; IFile file; private void createMarker(final String type) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { file = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor().getEditorInput().getAdapter(IFile.class); selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getSelectionService().getSelection(); if (selection instanceof ITextSelection) { final IMarker marker = MarkerFactory.createMarker(file, (ITextSelection) selection); MarkUtilities.setType(marker, type); AlloyUtilities.addTypeToMarker(marker); AlloyUtilities.addMarkerToRepository(marker); Visualization.showViz(MetaModelEditor.modelEditor); } } }); } @Override public void dragEnter(final DropTargetDragEvent dtde) { if (this.isDragOk(dtde) == false) { dtde.rejectDrag(); return; } dtde.acceptDrag(acceptableOps); } @Override public void dragExit(final DropTargetEvent dte) {} @Override public void dragOver(final DropTargetDragEvent dtde) { if (this.isDragOk(dtde) == false) { dtde.rejectDrag(); return; } dtde.acceptDrag(acceptableOps); } @SuppressWarnings("deprecation") @Override public void drop(final DropTargetDropEvent dtde) { final DataFlavor flavor = DataFlavor.stringFlavor; DataFlavor chosen = null; if (dtde.isLocalTransfer() == false) { chosen = DataFlavor.plainTextFlavor; } else { if (dtde.isDataFlavorSupported(flavor)) { chosen = flavor; } } if (chosen == null) { dtde.rejectDrop(); return; } final int sa = dtde.getSourceActions(); if ((sa & acceptableOps) == 0) { dtde.rejectDrop(); return; } Object data = null; try { dtde.acceptDrop(acceptableOps); data = dtde.getTransferable().getTransferData(chosen); if (data == null) { throw new NullPointerException(); } } catch (final Throwable t) { t.printStackTrace(); dtde.dropComplete(false); return; } final Point mousePoint = dtde.getLocation(); final GraphViewer graphViewer = (GraphViewer) dtde.getDropTargetContext().getComponent(); final Object annotation = graphViewer.alloyGetAnnotationAtXY(mousePoint.x, mousePoint.y); if (annotation instanceof AlloyAtom) { final AlloyAtom atom = (AlloyAtom) annotation; this.createMarker(atom.toString()); dtde.dropComplete(true); } } @Override public void dropActionChanged(final DropTargetDragEvent dtde) { if (this.isDragOk(dtde) == false) { dtde.rejectDrag(); return; } dtde.acceptDrag(acceptableOps); } private boolean isDragOk(final DropTargetDragEvent dtde) { final DataFlavor flavor = DataFlavor.stringFlavor; DataFlavor chosen = null; if (dtde.isDataFlavorSupported(flavor)) { chosen = flavor; } if (chosen == null) { return false; } final int sourceActions = dtde.getSourceActions(); if ((sourceActions & acceptableOps) == 0) { return false; } return true; } }, true); } public void create() { int index; this.textEditor = new TextEditor(); try { index = this.addPage(this.textEditor, this.getEditorInput()); this.setPageText(index, "Source"); this.setPartName(this.textEditor.getTitle()); } catch (final PartInitException e) { ErrorDialog.openError(this.getSite().getShell(), " Error creating nested text editor", null, e.getStatus()); } MetaModelEditor.modelEditor = new Composite(this.getContainer(), SWT.EMBEDDED); index = this.addPage(MetaModelEditor.modelEditor); this.setPageText(index, "Specification"); @SuppressWarnings("unused") final AlloyParserForMetamodel alloyParserForMetamodel = new AlloyParserForMetamodel( ((FileEditorInput) this.textEditor.getEditorInput()).getPath().toString()); MetaModelEditor.frame = null; MetaModelEditor.myState = null; MetaModelEditor.graph = null; MetaModelEditor.file = null; this.showMetamodel(true); } @Override protected void createPages() { this.create(); this.addDropListener(); } @Override public void doSave(final IProgressMonitor monitor) { // nothing } @Override public void doSaveAs() { // nothing } @Override public boolean isSaveAsAllowed() { return false; } private void showMetamodel(final boolean isMagicLayout) { MetaModelEditor.xmlFileName = Util.canon(AlloyUtilities.getLocationForMetamodel(this.textEditor.getTitle())); if (!AlloyUtilities.isExists()) { if (MetaModelEditor.frame != null) { if (MetaModelEditor.frame.getComponentCount() > 0) { MetaModelEditor.frame.removeAll(); } MetaModelEditor.frame.add(new JPanel()); } else if (MetaModelEditor.frame == null) { MetaModelEditor.frame = SWT_AWT.new_Frame(MetaModelEditor.modelEditor); MetaModelEditor.frame.add(new JPanel()); } return; } MetaModelEditor.file = new File(MetaModelEditor.xmlFileName); try { if (!MetaModelEditor.file.exists()) { throw new IOException("File " + MetaModelEditor.xmlFileName + " does not exist."); } // AlloyUtilities.setMetamodel(this.editor1.getTitle(), true); final AlloyInstance instance = StaticInstanceReader.parseInstance(MetaModelEditor.file); MetaModelEditor.myState = new VizState(instance); if (isMagicLayout == true) { MagicLayout.magic(MetaModelEditor.myState); MagicColor.magic(MetaModelEditor.myState); } else { MetaModelEditor.myState.resetTheme(); } if (MetaModelEditor.frame == null) { MetaModelEditor.frame = SWT_AWT.new_Frame(MetaModelEditor.modelEditor); } if (MetaModelEditor.graph != null && MetaModelEditor.frame.getComponent(0) != null) { MetaModelEditor.frame.remove(MetaModelEditor.graph); } MetaModelEditor.graph = new VizGraphPanel(MetaModelEditor.myState, false); MetaModelEditor.frame.removeAll(); MetaModelEditor.frame.add(MetaModelEditor.graph); MetaModelEditor.frame.setVisible(true); MetaModelEditor.frame.setAlwaysOnTop(true); MetaModelEditor.graph.alloyGetViewer().alloyRepaint(); final JMenuItem magicLayoutMenuItem = new JMenuItem("Magic Layout"); final JMenuItem resetThemeMenuItem = new JMenuItem("Reset Theme"); MetaModelEditor.graph.alloyGetViewer().pop.add(magicLayoutMenuItem, 0); MetaModelEditor.graph.alloyGetViewer().pop.add(resetThemeMenuItem, 1); magicLayoutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MetaModelEditor.this.showMetamodel(true); } }); resetThemeMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MetaModelEditor.this.showMetamodel(false); } }); } catch (final Err e1) { e1.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } } }
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; public class ContactDeletionTest extends TestBase { @Test public void testContactDeletion() { app.goToHomePage(); if (! app.getContactHelper().isThereAContact()) { app.getNavigationHelper().goToAddNewPage(); app.getContactHelper().createContact(new ContactData("Daria", "Churkina", "123", "daria.churkina@inbox.ru", "Test1")); app.goToHomePage(); } app.getContactHelper().selectContact(); app.getContactHelper().deleteSelectedContact(); app.getAccept(); app.goToHomePage(); } }
package io.qameta.allure.junit4; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.junit.runner.notification.RunNotifier; /** * @author Egor Borisov ehborisov@gmail.com */ @Aspect public class AllureJunit4ListenerAspect { private final AllureJunit4 allure = new AllureJunit4(); @After("execution(org.junit.runner.notification.RunNotifier.new())") public void addListener(final JoinPoint point) { final RunNotifier notifier = (RunNotifier) point.getThis(); notifier.removeListener(allure); notifier.addListener(allure); } }
package com.mashape.analytics.agent.filter; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.servlet.AsyncContext; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.mashape.analytics.agent.connection.ConnectionManager; import com.mashape.analytics.agent.mapper.AnalyticsDataMapper; import com.mashape.analytics.agent.modal.Message; import com.mashape.analytics.agent.wrapper.RequestInterceptorWrapper; import com.mashape.analytics.agent.wrapper.ResponseInterceptorWrapper; public class AnalyticsFilter implements Filter { final static Logger logger = Logger.getLogger(AnalyticsFilter.class); public static final String ANALYTICS_SERVER_URL = "analyticsServerUrl"; public static final String ANALYTICS_SERVER_PORT = "analyticsServerPort"; protected static final String ANALYTICS_DATA = "data"; private ExecutorService analyticsServicexeExecutor; private int poolSize; FilterConfig config; private String analyticsServerUrl; private String analyticsServerPort; @Override public void destroy() { analyticsServicexeExecutor.shutdown(); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { Date requestReceivedTime = new Date(); RequestInterceptorWrapper request = new RequestInterceptorWrapper( (HttpServletRequest) req); ResponseInterceptorWrapper response = new ResponseInterceptorWrapper( (HttpServletResponse) res); long startTime = System.currentTimeMillis(); chain.doFilter(request, response); long endTime = System.currentTimeMillis(); Map<String, String> messageProperties = new HashMap<String, String>(); messageProperties.put(ANALYTICS_SERVER_URL, analyticsServerUrl); messageProperties.put(ANALYTICS_SERVER_PORT, analyticsServerPort); AnalyticsDataMapper mapper = new AnalyticsDataMapper(request, response, config); Message analyticsData = mapper.getAnalyticsData( requestReceivedTime, startTime, endTime); String data = new Gson().toJson(analyticsData); logger.debug(data); messageProperties.put(ANALYTICS_DATA, data); ConnectionManager.sendMessage(messageProperties); } catch (Throwable x) { logger.error("Failed to send analytics data", x); } } @Override public void init(FilterConfig config) throws ServletException { this.config = config; poolSize = Integer.parseInt(config.getInitParameter("poolSize")); analyticsServicexeExecutor = Executors.newFixedThreadPool(poolSize); analyticsServerUrl = config.getInitParameter("analyticsServerUrl"); analyticsServerPort = config.getInitParameter("analyticsServerPort"); } }
package org.jboss.seam.faces.component; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Arrays; import javax.el.ELContext; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.MethodExpression; import javax.el.MethodInfo; import javax.el.ValueExpression; import javax.faces.component.StateHolder; import javax.faces.context.FacesContext; import javax.faces.el.EvaluationException; import javax.faces.el.MethodBinding; import javax.faces.el.MethodNotFoundException; /** * <p> * Wrap a MethodExpression instance and expose it as a MethodBinding * </p> * */ class MethodBindingMethodExpressionAdapter extends MethodBinding implements StateHolder, Serializable { private static final long serialVersionUID = 7334926223014401689L; private MethodExpression methodExpression = null; private boolean tranzient; public MethodBindingMethodExpressionAdapter() { } // for StateHolder MethodBindingMethodExpressionAdapter(final MethodExpression methodExpression) { this.methodExpression = methodExpression; } @Override @SuppressWarnings("deprecation") public Object invoke(final FacesContext context, final Object params[]) throws EvaluationException, MethodNotFoundException { assert (null != methodExpression); if (context == null) { throw new NullPointerException("FacesConext -> null"); } Object result = null; try { result = methodExpression.invoke(context.getELContext(), params); } catch (javax.el.MethodNotFoundException e) { throw new javax.faces.el.MethodNotFoundException(e); } catch (javax.el.PropertyNotFoundException e) { throw new EvaluationException(e); } catch (ELException e) { Throwable cause = e.getCause(); if (cause == null) { cause = e; } throw new EvaluationException(cause); } catch (NullPointerException e) { throw new MethodNotFoundException(e); } return result; } @Override @SuppressWarnings("deprecation") public Class<?> getType(final FacesContext context) throws MethodNotFoundException { assert (null != methodExpression); if (context == null) { throw new NullPointerException("FacesConext -> null"); } Class<?> result = null; if (context == null) { throw new NullPointerException(); } try { MethodInfo mi = methodExpression.getMethodInfo(context.getELContext()); result = mi.getReturnType(); } catch (javax.el.PropertyNotFoundException e) { throw new MethodNotFoundException(e); } catch (javax.el.MethodNotFoundException e) { throw new MethodNotFoundException(e); } catch (ELException e) { throw new MethodNotFoundException(e); } return result; } @Override public String getExpressionString() { assert (null != methodExpression); return methodExpression.getExpressionString(); } @Override @SuppressWarnings("deprecation") public boolean equals(final Object other) { if (this == other) { return true; } if (other instanceof MethodBindingMethodExpressionAdapter) { return methodExpression.equals(((MethodBindingMethodExpressionAdapter) other).getWrapped()); } else if (other instanceof MethodBinding) { MethodBinding binding = (MethodBinding) other; // We'll need to do a little leg work to determine // if the MethodBinding is equivalent to the // wrapped MethodExpression String expr = binding.getExpressionString(); int idx = expr.indexOf('.'); String target = expr.substring(0, idx).substring(2); String t = expr.substring(idx + 1); String method = t.substring(0, (t.length() - 1)); FacesContext context = FacesContext.getCurrentInstance(); ELContext elContext = context.getELContext(); MethodInfo controlInfo = methodExpression.getMethodInfo(elContext); // ensure the method names are the same if (!controlInfo.getName().equals(method)) { return false; } // Using the target, create an expression and evaluate ExpressionFactory factory = context.getApplication().getExpressionFactory(); ValueExpression ve = factory.createValueExpression(elContext, "#{" + target + '}', Object.class); if (ve == null) { return false; } Object result = ve.getValue(elContext); if (result == null) { return false; } // Get all of the methods with the matching name and try // to find a match based on controlInfo's return and parameter // types Class<?> type = binding.getType(context); Method[] methods = result.getClass().getMethods(); for (Method meth : methods) { if (meth.getName().equals(method) && type.equals(controlInfo.getReturnType()) && Arrays.equals(meth.getParameterTypes(), controlInfo.getParamTypes())) { return true; } } } return false; } @Override public int hashCode() { assert (null != methodExpression); return methodExpression.hashCode(); } public boolean isTransient() { return this.tranzient; } public void setTransient(final boolean tranzient) { this.tranzient = tranzient; } public Object saveState(final FacesContext context) { if (context == null) { throw new NullPointerException(); } Object result = null; if (!tranzient) { if (methodExpression instanceof StateHolder) { Object[] stateStruct = new Object[2]; // save the actual state of our wrapped methodExpression stateStruct[0] = ((StateHolder) methodExpression).saveState(context); // save the class name of the methodExpression impl stateStruct[1] = methodExpression.getClass().getName(); result = stateStruct; } else { result = methodExpression; } } return result; } public void restoreState(final FacesContext context, final Object state) { if (context == null) { throw new NullPointerException(); } // if we have state if (null == state) { return; } if (!(state instanceof MethodExpression)) { Object[] stateStruct = (Object[]) state; Object savedState = stateStruct[0]; String className = stateStruct[1].toString(); MethodExpression result = null; Class<?> toRestoreClass = null; if (null != className) { try { toRestoreClass = loadClass(className, this); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage()); } if (null != toRestoreClass) { try { result = (MethodExpression) toRestoreClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e.getMessage()); } catch (IllegalAccessException a) { throw new IllegalStateException(a.getMessage()); } } if ((null != result) && (null != savedState)) { // don't need to check transient, since that was // done on the saving side. ((StateHolder) result).restoreState(context, savedState); } methodExpression = result; } } else { methodExpression = (MethodExpression) state; } } public MethodExpression getWrapped() { return methodExpression; } // Helper methods for StateHolder private static Class<?> loadClass(final String name, final Object fallbackClass) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = fallbackClass.getClass().getClassLoader(); } return Class.forName(name, true, loader); } }
package es.craftsmanship.toledo.katangapp.activities; import android.app.Dialog; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; public abstract class BaseGeoLocatedActivity extends BaseAndroidBusRegistrableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final LocationRequest GPS_REQUEST = LocationRequest.create() .setInterval(10000) .setFastestInterval(3000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200; private GoogleApiClient googleApiClient; private Double latitude; private Double longitude; @Override public void onConnected(Bundle bundle) { Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (lastLocation != null) { longitude = lastLocation.getLongitude(); latitude = lastLocation.getLatitude(); } LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, GPS_REQUEST, this); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { if (location != null) { longitude = location.getLongitude(); latitude = location.getLatitude(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode != REQUEST_CODE_RECOVER_PLAY_SERVICES) { return; } if (resultCode == RESULT_OK) { if (!googleApiClient.isConnecting() && !googleApiClient.isConnected()) { googleApiClient.connect(); } } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this, "Google Play Services must be installed.", Toast.LENGTH_SHORT).show(); finish(); } } protected Double getLatitude() { return latitude; } protected Double getLongitude() { return longitude; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeGooglePlayServices(); } @Override protected void onPause() { if (googleApiClient != null) { googleApiClient.disconnect(); } super.onPause(); } @Override protected void onResume() { super.onResume(); if (googleApiClient != null) { googleApiClient.connect(); } } private void initializeGooglePlayServices() { int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { /* * google play services is missing or update is required * return code could be * SUCCESS, * SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED, * SERVICE_DISABLED, SERVICE_INVALID. */ Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( checkGooglePlayServices, this, REQUEST_CODE_RECOVER_PLAY_SERVICES); errorDialog.show(); return; } googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } }
package nodomain.freeyourgadget.gadgetbridge.devices.qhybrid; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.GBException; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.activities.AbstractGBActivity; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.model.GenericItem; import nodomain.freeyourgadget.gadgetbridge.model.ItemWithDetails; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.DeviceInfo; import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.QHybridSupport; import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.fossil.FossilWatchAdapter; import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.buttonconfig.ConfigPayload; import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.FossilRequest; import nodomain.freeyourgadget.gadgetbridge.util.GB; public class ConfigActivity extends AbstractGBActivity { PackageAdapter adapter; ArrayList<NotificationConfiguration> list; PackageConfigHelper helper; final int REQUEST_CODE_ADD_APP = 0; private boolean hasControl = false; SharedPreferences prefs; TextView timeOffsetView, timezoneOffsetView; GBDevice device; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qhybrid_settings); findViewById(R.id.buttonOverwriteButtons).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_OVERWRITE_BUTTONS)); } }); prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE); timeOffsetView = findViewById(R.id.qhybridTimeOffset); timeOffsetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int timeOffset = prefs.getInt("QHYBRID_TIME_OFFSET", 0); LinearLayout layout2 = new LinearLayout(ConfigActivity.this); layout2.setOrientation(LinearLayout.HORIZONTAL); final NumberPicker hourPicker = new NumberPicker(ConfigActivity.this); hourPicker.setMinValue(0); hourPicker.setMaxValue(23); hourPicker.setValue(timeOffset / 60); final NumberPicker minPicker = new NumberPicker(ConfigActivity.this); minPicker.setMinValue(0); minPicker.setMaxValue(59); minPicker.setValue(timeOffset % 60); layout2.addView(hourPicker); TextView tw = new TextView(ConfigActivity.this); tw.setText(":"); layout2.addView(tw); layout2.addView(minPicker); layout2.setGravity(Gravity.CENTER); new AlertDialog.Builder(ConfigActivity.this) .setTitle("offset time by") .setView(layout2) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { prefs.edit().putInt("QHYBRID_TIME_OFFSET", hourPicker.getValue() * 60 + minPicker.getValue()).apply(); updateTimeOffset(); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE)); Toast.makeText(ConfigActivity.this, "change might take some seconds...", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("cancel", null) .show(); } }); updateTimeOffset(); timezoneOffsetView = findViewById(R.id.timezoneOffset); timezoneOffsetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int timeOffset = prefs.getInt("QHYBRID_TIMEZONE_OFFSET", 0); LinearLayout layout2 = new LinearLayout(ConfigActivity.this); layout2.setOrientation(LinearLayout.HORIZONTAL); final NumberPicker hourPicker = new NumberPicker(ConfigActivity.this); hourPicker.setMinValue(0); hourPicker.setMaxValue(23); hourPicker.setValue(timeOffset / 60); final NumberPicker minPicker = new NumberPicker(ConfigActivity.this); minPicker.setMinValue(0); minPicker.setMaxValue(59); minPicker.setValue(timeOffset % 60); layout2.addView(hourPicker); TextView tw = new TextView(ConfigActivity.this); tw.setText(":"); layout2.addView(tw); layout2.addView(minPicker); layout2.setGravity(Gravity.CENTER); new AlertDialog.Builder(ConfigActivity.this) .setTitle("offset timezone by") .setView(layout2) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { prefs.edit().putInt("QHYBRID_TIMEZONE_OFFSET", hourPicker.getValue() * 60 + minPicker.getValue()).apply(); updateTimezoneOffset(); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_TIMEZONE)); Toast.makeText(ConfigActivity.this, "change might take some seconds...", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("cancel", null) .show(); } }); updateTimezoneOffset(); setTitle(R.string.preferences_qhybrid_settings); ListView appList = findViewById(R.id.qhybrid_appList); try { helper = new PackageConfigHelper(getApplicationContext()); list = helper.getNotificationConfigurations(); } catch (GBException e) { e.printStackTrace(); GB.toast("error getting configurations", Toast.LENGTH_SHORT, GB.ERROR, e); list = new ArrayList<>(); } list.add(null); appList.setAdapter(adapter = new PackageAdapter(this, R.layout.qhybrid_package_settings_item, list)); appList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) { PopupMenu menu = new PopupMenu(ConfigActivity.this, view); menu.getMenu().add("edit"); menu.getMenu().add("delete"); menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getTitle().toString()) { case "edit": { TimePicker picker = new TimePicker(ConfigActivity.this, (NotificationConfiguration) adapterView.getItemAtPosition(i)); picker.finishListener = new TimePicker.OnFinishListener() { @Override public void onFinish(boolean success, NotificationConfiguration config) { setControl(false, null); if (success) { try { helper.saveNotificationConfiguration(config); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION_CONFIG_CHANGED)); } catch (GBException e) { e.printStackTrace(); GB.toast("error saving notification", Toast.LENGTH_SHORT, GB.ERROR, e); } refreshList(); } } }; picker.handsListener = new TimePicker.OnHandsSetListener() { @Override public void onHandsSet(NotificationConfiguration config) { setHands(config); } }; picker.vibrationListener = new TimePicker.OnVibrationSetListener() { @Override public void onVibrationSet(NotificationConfiguration config) { vibrate(config); } }; setControl(true, picker.getSettings()); break; } case "delete": { try { helper.deleteNotificationConfiguration((NotificationConfiguration) adapterView.getItemAtPosition(i)); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION_CONFIG_CHANGED)); } catch (GBException e) { e.printStackTrace(); GB.toast("error deleting setting", Toast.LENGTH_SHORT, GB.ERROR, e); } refreshList(); break; } } return true; } }); menu.show(); return true; } }); appList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent notificationIntent = new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION); notificationIntent.putExtra("CONFIG", (NotificationConfiguration) adapterView.getItemAtPosition(i)); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(notificationIntent); } }); SeekBar vibeBar = findViewById(R.id.vibrationStrengthBar); vibeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int start; @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { start = seekBar.getProgress(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress; if ((progress = seekBar.getProgress()) == start) return; String[] values = {"25", "50", "100"}; device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_VIBRATION_STRENGTH, values[progress])); Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS); intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_VIBRATION_STRENGTH); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent); } }); device = GBApplication.app().getDeviceManager().getSelectedDevice(); if (device == null || device.getType() != DeviceType.FOSSILQHYBRID) { setSettingsError("Watch not connected"); } else { updateSettings(); } } private void updateTimeOffset() { int timeOffset = prefs.getInt("QHYBRID_TIME_OFFSET", 0); DecimalFormat format = new DecimalFormat("00"); timeOffsetView.setText( format.format(timeOffset / 60) + ":" + format.format(timeOffset % 60) ); } private void updateTimezoneOffset() { int timeOffset = prefs.getInt("QHYBRID_TIMEZONE_OFFSET", 0); DecimalFormat format = new DecimalFormat("00"); timezoneOffsetView.setText( format.format(timeOffset / 60) + ":" + format.format(timeOffset % 60) ); } private void setSettingsEnabled(boolean enables) { findViewById(R.id.settingsLayout).setAlpha(enables ? 1f : 0.2f); } private void updateSettings() { runOnUiThread(new Runnable() { @Override public void run() { EditText et = findViewById(R.id.stepGoalEt); et.setOnEditorActionListener(null); final String text = device.getDeviceInfo(QHybridSupport.ITEM_STEP_GOAL).getDetails(); et.setText(text); et.setSelection(text.length()); et.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (i == EditorInfo.IME_ACTION_DONE || i == EditorInfo.IME_ACTION_NEXT) { String t = textView.getText().toString(); if (!t.isEmpty()) { device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_STEP_GOAL, t)); Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS); intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_STEP_GOAL); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent); updateSettings(); } ((InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } return true; } }); if (device.getDeviceInfo(QHybridSupport.ITEM_EXTENDED_VIBRATION_SUPPORT).getDetails().equals("true")) { final int strengthProgress = (int) (Math.log(Double.parseDouble(device.getDeviceInfo(QHybridSupport.ITEM_VIBRATION_STRENGTH).getDetails()) / 25) / Math.log(2)); setSettingsEnabled(true); SeekBar seekBar = findViewById(R.id.vibrationStrengthBar); seekBar.setProgress(strengthProgress); } else { findViewById(R.id.vibrationStrengthBar).setEnabled(false); findViewById(R.id.vibrationStrengthLayout).setAlpha(0.5f); } CheckBox activityHandCheckbox = findViewById(R.id.checkBoxUserActivityHand); if (device.getDeviceInfo(QHybridSupport.ITEM_HAS_ACTIVITY_HAND).getDetails().equals("true")) { if (device.getDeviceInfo(QHybridSupport.ITEM_USE_ACTIVITY_HAND).getDetails().equals("true")) { activityHandCheckbox.setChecked(true); } activityHandCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean checked) { if (!device.getDeviceInfo(QHybridSupport.ITEM_STEP_GOAL).getDetails().equals("1000000")) { new AlertDialog.Builder(ConfigActivity.this) .setMessage("Please set the step count to a million to activate that.") .setPositiveButton("ok", null) .show(); buttonView.setChecked(false); return; } device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_USE_ACTIVITY_HAND, String.valueOf(checked))); Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS); intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_USE_ACTIVITY_HAND); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent); } }); } else { // activityHandCheckbox.setEnabled(false); activityHandCheckbox.setAlpha(0.2f); activityHandCheckbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GB.toast("nah.", Toast.LENGTH_SHORT, GB.INFO); ((CheckBox) v).setChecked(false); } }); } final String buttonJson = device.getDeviceInfo(FossilWatchAdapter.ITEM_BUTTONS).getDetails(); try { JSONArray buttonConfig_; if (buttonJson == null || buttonJson.isEmpty()) { buttonConfig_ = new JSONArray(new String[]{"", "", ""}); }else{ buttonConfig_ = new JSONArray(buttonJson); } final JSONArray buttonConfig = buttonConfig_; LinearLayout buttonLayout = findViewById(R.id.buttonConfigLayout); buttonLayout.removeAllViews(); findViewById(R.id.buttonOverwriteButtons).setVisibility(View.GONE); final ConfigPayload[] payloads = ConfigPayload.values(); final String[] names = new String[payloads.length]; for (int i = 0; i < payloads.length; i++) names[i] = payloads[i].getDescription(); for (int i = 0; i < buttonConfig.length(); i++) { final int currentIndex = i; String configName = buttonConfig.getString(i); TextView buttonTextView = new TextView(ConfigActivity.this); buttonTextView.setTextColor(Color.WHITE); buttonTextView.setTextSize(20); try { ConfigPayload payload = ConfigPayload.valueOf(configName); buttonTextView.setText("Button " + (i + 1) + ": " + payload.getDescription()); } catch (IllegalArgumentException e) { buttonTextView.setText("Button " + (i + 1) + ": Unknown"); } buttonTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog dialog = new AlertDialog.Builder(ConfigActivity.this) .setItems(names, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); ConfigPayload selected = payloads[which]; try { buttonConfig.put(currentIndex, selected.toString()); device.addDeviceInfo(new GenericItem(FossilWatchAdapter.ITEM_BUTTONS, buttonConfig.toString())); updateSettings(); Intent buttonIntent = new Intent(QHybridSupport.QHYBRID_COMMAND_OVERWRITE_BUTTONS); buttonIntent.putExtra(FossilWatchAdapter.ITEM_BUTTONS, buttonConfig.toString()); LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(buttonIntent); } catch (JSONException e) { e.printStackTrace(); } } }) .setTitle("Button " + (currentIndex + 1)) .create(); dialog.show(); } }); buttonLayout.addView(buttonTextView); } } catch (JSONException e) { e.printStackTrace(); GB.toast("error parsing button config", Toast.LENGTH_LONG, GB.ERROR); } } }); } private void setControl(boolean control, NotificationConfiguration config) { if (hasControl == control) return; Intent intent = new Intent(control ? QHybridSupport.QHYBRID_COMMAND_CONTROL : QHybridSupport.QHYBRID_COMMAND_UNCONTROL); intent.putExtra("CONFIG", config); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); this.hasControl = control; } private void setHands(NotificationConfiguration config) { sendControl(config, QHybridSupport.QHYBRID_COMMAND_SET); } private void vibrate(NotificationConfiguration config) { sendControl(config, QHybridSupport.QHYBRID_COMMAND_VIBRATE); } private void sendControl(NotificationConfiguration config, String request) { Intent intent = new Intent(request); intent.putExtra("CONFIG", config); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } private void refreshList() { list.clear(); try { list.addAll(helper.getNotificationConfigurations()); } catch (GBException e) { e.printStackTrace(); GB.toast("error getting configurations", Toast.LENGTH_SHORT, GB.ERROR, e); } list.add(null); adapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onResume() { super.onResume(); refreshList(); registerReceiver(buttonReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_BUTTON_PRESS)); LocalBroadcastManager.getInstance(this).registerReceiver(settingsReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_SETTINGS_UPDATED)); LocalBroadcastManager.getInstance(this).registerReceiver(fileReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_FILE_UPLOADED)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(buttonReceiver); LocalBroadcastManager.getInstance(this).unregisterReceiver(settingsReceiver); LocalBroadcastManager.getInstance(this).unregisterReceiver(fileReceiver); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } private void setSettingsError(final String error) { runOnUiThread(new Runnable() { @Override public void run() { setSettingsEnabled(false); ((TextView) findViewById(R.id.settingsErrorText)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.settingsErrorText)).setText(error); } }); } class PackageAdapter extends ArrayAdapter<NotificationConfiguration> { PackageManager manager; PackageAdapter(@NonNull Context context, int resource, @NonNull List<NotificationConfiguration> objects) { super(context, resource, objects); manager = context.getPackageManager(); } @NonNull @Override public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) { if (!(view instanceof RelativeLayout)) view = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.qhybrid_package_settings_item, null); NotificationConfiguration settings = getItem(position); if (settings == null) { Button addButton = new Button(ConfigActivity.this); addButton.setText("+"); addButton.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivityForResult(new Intent(ConfigActivity.this, QHybridAppChoserActivity.class), REQUEST_CODE_ADD_APP); } }); return addButton; } try { ((ImageView) view.findViewById(R.id.packageIcon)).setImageDrawable(manager.getApplicationIcon(settings.getPackageName())); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } final int width = 100; ((TextView) view.findViewById(R.id.packageName)).setText(settings.getAppName()); Bitmap bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bitmap); Paint black = new Paint(); black.setColor(Color.BLACK); black.setStyle(Paint.Style.STROKE); black.setStrokeWidth(5); c.drawCircle(width / 2, width / 2, width / 2 - 3, black); int center = width / 2; if (settings.getHour() != -1) { c.drawLine( center, center, (float) (center + Math.sin(Math.toRadians(settings.getHour())) * (width / 4)), (float) (center - Math.cos(Math.toRadians(settings.getHour())) * (width / 4)), black ); } if (settings.getMin() != -1) { c.drawLine( center, center, (float) (center + Math.sin(Math.toRadians(settings.getMin())) * (width / 3)), (float) (center - Math.cos(Math.toRadians(settings.getMin())) * (width / 3)), black ); } ((ImageView) view.findViewById(R.id.packageClock)).setImageBitmap(bitmap); return view; } } BroadcastReceiver fileReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean error = intent.getBooleanExtra("EXTRA_ERROR", false); if (error) { Toast.makeText(ConfigActivity.this, "Error overwriting buttons", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(ConfigActivity.this, "Successfully overwritten buttons", Toast.LENGTH_SHORT).show(); } }; BroadcastReceiver buttonReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(ConfigActivity.this, "Button " + intent.getIntExtra("BUTTON", -1) + " pressed", Toast.LENGTH_SHORT).show(); } }; BroadcastReceiver settingsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(ConfigActivity.this, "Setting updated", Toast.LENGTH_SHORT).show(); updateSettings(); } }; }
package org.csstudio.vtype.pv.pva; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import org.csstudio.vtype.pv.PV; import org.epics.pvaccess.client.ChannelPut; import org.epics.pvaccess.client.ChannelPutRequester; import org.epics.pvdata.factory.PVDataFactory; import org.epics.pvdata.misc.BitSet; import org.epics.pvdata.pv.PVField; import org.epics.pvdata.pv.PVStructure; import org.epics.pvdata.pv.Status; import org.epics.pvdata.pv.Structure; /** A {@link ChannelPutRequester} for writing a value to a {@link PVA_PV}, * indicating completion via a {@link Future} * * @author Kay Kasemir */ @SuppressWarnings("nls") class PVPutHandler extends PVRequester implements ChannelPutRequester, Future<Object> { final private PV pv; final private Object new_value; final private CountDownLatch updates = new CountDownLatch(1); private volatile Exception error = null; /** @param pv PV to write * @param new_value Value to write */ public PVPutHandler(PV pv, Object new_value) { this.pv = pv; this.new_value = new_value; } // ChannelPutRequester @Override public void channelPutConnect(final Status status, final ChannelPut channelPut, final Structure structure) { if (! status.isSuccess()) { error = new Exception("Failed to connect 'put' for " + pv.getName() + ": " + status); updates.countDown(); return; } try { final PVStructure write_structure = PVDataFactory.getPVDataCreate().createPVStructure(structure); final BitSet bit_set = new BitSet(write_structure.getNumberFields()); // Locate the value field at deepest level in structure PVField field = null; PVStructure search = write_structure; while (search != null) { final PVField[] fields = search.getPVFields(); if (fields.length != 1) throw new Exception("Can only write to simple struct.element.value path, got " + structure); if (fields[0].getFieldName().equals("value")) { field = fields[0]; break; } else if (fields[0] instanceof PVStructure) search = (PVStructure) fields[0]; else search = null; } if (field == null) throw new Exception("Cannot locate 'value' to write in " + structure); // Enumerated? Write to value.index if (field instanceof PVStructure && "enum_t".equals(field.getField().getID())) field = ((PVStructure)field).getSubField("index"); // Indicate what's changed & change it bit_set.set(field.getFieldOffset()); PVStructureHelper.setField(field, new_value); // Perform write channelPut.put(write_structure, bit_set); } catch (Exception ex) { logger.log(Level.WARNING, "Failed to write " + pv.getName() + " = " + new_value, ex); error = new Exception("Failed to write " + pv.getName() + " = " + new_value, ex); updates.countDown(); } } // ChannelPutRequester @Override public void putDone(final Status status, final ChannelPut channelPut) { if (status.isSuccess()) logger.log(Level.FINE, "Write {0} = {1} completed", new Object[] { pv.getName(), new_value }); else { error = new Exception("Write " + pv.getName() + " = " + new_value + " failed, " + status.toString()); logger.log(Level.WARNING, "", error); } updates.countDown(); channelPut.destroy(); } // ChannelPutRequester @Override public void getDone(final Status status, final ChannelPut channelPut, final PVStructure pvStructure, final BitSet bitSet) { // Only used for createChannelPutGet logger.log(Level.WARNING, "Unexpected call to ChannelPutRequester.getDone(), channel {0}", channelPut.getChannel().getChannelName()); } // Future @Override public boolean cancel(final boolean mayInterruptIfRunning) { return false; } // Future @Override public boolean isCancelled() { return false; } // Future @Override public boolean isDone() { return updates.getCount() == 0; } // Future @Override public Object get() throws InterruptedException, ExecutionException { updates.await(); if (error != null) throw new ExecutionException(error); return null; } // Future @Override public Object get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (! updates.await(timeout, unit)) throw new TimeoutException(pv.getName() + " write timeout"); if (error != null) throw new ExecutionException(error); return null; } }
package org.ccnx.ccn.io; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.Arrays; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.CCNFlowControl; import org.ccnx.ccn.impl.CCNSegmenter; import org.ccnx.ccn.impl.CCNFlowControl.Shape; import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper; import org.ccnx.ccn.impl.security.crypto.ContentKeys; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.SignedInfo.ContentType; /** * Basic output stream class which generates segmented content under a given * name prefix. Segment naming is generated according to the SegmentationProfile; * by default names are sequentially numbered. Name prefixes are taken as specified * (no versions or other information is added by this class). Segments are * fixed length (see CCNBlockOutputStream for non fixed-length segments). */ public class CCNOutputStream extends CCNAbstractOutputStream { /** * Amount of data we keep around prior to forced flush, in terms of segmenter * blocks. We write to a limit lower than the maximum, to allow for expansion * due to encryption. * TODO calculate this dynamically based on the bulk signing method and overhead thereof */ public static final int BLOCK_BUF_COUNT = 128; /** * elapsed length written */ protected long _totalLength = 0; /** * write pointer - offset into the write buffer at which to write */ protected int _blockOffset = 0; /** * write buffer */ protected byte [] _buffer = null; /** * base name index of the current set of data to output; * incremented according to the segmentation profile. */ protected long _baseNameIndex; /** * // timestamp we use for writing, set to time first segment is written */ protected CCNTime _timestamp; /** * type of content null == DATA (or ENCR if encrypted) */ protected ContentType _type; protected CCNDigestHelper _dh; /** * Constructor for a simple CCN output stream. * @param name name prefix under which to write content segments * @param handle if null, new handle created with CCNHandle#open() * @throws IOException if stream setup fails */ public CCNOutputStream(ContentName name, CCNHandle handle) throws IOException { this(name, (PublisherPublicKeyDigest)null, handle); } /** * Constructor for a simple CCN output stream. * @param name name prefix under which to write content segments * @param publisher key to use to sign the segments, if null, default for user is used. * @param handle if null, new handle created with CCNHandle#open() * @throws IOException if stream setup fails */ public CCNOutputStream(ContentName name, PublisherPublicKeyDigest publisher, CCNHandle handle) throws IOException { this(name, null, publisher, null, null, handle); } /** * Constructor for a simple CCN output stream. * @param name name prefix under which to write content segments * @param keys keys with which to encrypt content, if null content either unencrypted * or keys retrieved according to local policy * @param handle if null, new handle created with CCNHandle#open() * @throws IOException if stream setup fails */ public CCNOutputStream(ContentName name, ContentKeys keys, CCNHandle handle) throws IOException { this(name, null, null, null, keys, handle); } /** * Constructor for a simple CCN output stream. * @param name name prefix under which to write content segments * @param locator key locator to use, if null, default for key is used. * @param publisher key to use to sign the segments, if null, default for user is used. * @param keys keys with which to encrypt content, if null content either unencrypted * or keys retrieved according to local policy * @param handle if null, new handle created with CCNHandle#open() * @throws IOException if stream setup fails */ public CCNOutputStream(ContentName name, KeyLocator locator, PublisherPublicKeyDigest publisher, ContentKeys keys, CCNHandle handle) throws IOException { this(name, locator, publisher, null, keys, handle); } /** * Constructor for a simple CCN output stream. * @param name name prefix under which to write content segments * @param locator key locator to use, if null, default for key is used. * @param publisher key to use to sign the segments, if null, default for user is used. * @param type type to mark content (see ContentType), if null, DATA is used; if * content encrypted, ENCR is used. * @param keys keys with which to encrypt content, if null content either unencrypted * or keys retrieved according to local policy * @param handle if null, new handle created with CCNHandle#open() * @throws IOException if stream setup fails */ public CCNOutputStream(ContentName name, KeyLocator locator, PublisherPublicKeyDigest publisher, ContentType type, ContentKeys keys, CCNHandle handle) throws IOException { this(name, locator, publisher, type, keys, new CCNFlowControl(name, handle)); } /** * Special purpose constructor. */ protected CCNOutputStream() {} /** * Low-level constructor used by clients that need to specify flow control behavior. * @param name name prefix under which to write content segments * @param locator key locator to use, if null, default for key is used. * @param publisher key to use to sign the segments, if null, default for user is used. * @param type type to mark content (see ContentType), if null, DATA is used; if * content encrypted, ENCR is used. * @param keys keys with which to encrypt content, if null content either unencrypted * or keys retrieved according to local policy * @param flowControl flow controller used to buffer output content * @throws IOException if flow controller setup fails */ public CCNOutputStream(ContentName name, KeyLocator locator, PublisherPublicKeyDigest publisher, ContentType type, ContentKeys keys, CCNFlowControl flowControl) throws IOException { this(name, locator, publisher, type, new CCNSegmenter(flowControl, null, keys)); } /** * Low-level constructor used by subclasses that need to specify segmenter behavior. * @param name name prefix under which to write content segments * @param locator key locator to use, if null, default for key is used. * @param publisher key to use to sign the segments, if null, default for user is used. * @param type type to mark content (see ContentType), if null, DATA is used; if * content encrypted, ENCR is used. * @param segmenter segmenter used to segment and sign content, should be already initialized * with ContentKeys if needed. * @throws IOException if flow controller setup fails */ protected CCNOutputStream(ContentName name, KeyLocator locator, PublisherPublicKeyDigest publisher, ContentType type, CCNSegmenter segmenter) throws IOException { super(locator, publisher, segmenter); ContentName nameToOpen = name; if (SegmentationProfile.isSegment(nameToOpen)) { nameToOpen = SegmentationProfile.segmentRoot(nameToOpen); // DKS -- should we offset output index to next one? might have closed // previous stream, so likely not } // Should have name of root of version we want to open. _baseName = nameToOpen; _buffer = new byte[BLOCK_BUF_COUNT * segmenter.getBlockSize()]; _baseNameIndex = SegmentationProfile.baseSegment(); _type = type; // null = DATA or ENCR _dh = new CCNDigestHelper(); startWrite(); // set up flow controller to write } @Override protected void startWrite() throws IOException { _segmenter.getFlowControl().startWrite(_baseName, Shape.STREAM); } /** * Set the segmentation block size to use. Constraints: needs to be * a multiple of the likely encryption block size (which is, conservatively, 32 bytes). * Default is 4096. * @param blockSize in bytes */ public void setBlockSize(int blockSize) { if (blockSize <= 0) { throw new IllegalArgumentException("Cannot set negative or zero block size!"); } // We have an existing buffer. That might contain existing data. Changing the // buffer size here to get the right number of blocks might require a forced flush // or all sorts of complicated hijinks. For now, just stick with the same buffer; // if we manage to go buffer-free, this won't matter. getSegmenter().setBlockSize(blockSize); } /** * Get segmentation block size. * @return block size in bytes */ public int getBlockSize() { return getSegmenter().getBlockSize(); } @Override public void close() throws IOException { try { _segmenter.getFlowControl().beforeClose(); closeNetworkData(); _segmenter.getFlowControl().afterClose(); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } catch (InterruptedException e) { throw new IOException("Low-level network failure!: " + e.getMessage()); } } @Override public void flush() throws IOException { flush(false); // if there is a partial block, don't flush it } /** * Internal flush. * @param flushLastBlock Should we flush the last (partial) block, or hold it back * for it to be filled. * @throws IOException on a variety of types of error. */ protected void flush(boolean flushLastBlock) throws IOException { try { flushToNetwork(flushLastBlock); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } catch (InterruptedException e) { throw new IOException("Low-level network failure!: " + e.getMessage()); } catch (InvalidAlgorithmParameterException e) { throw new IOException("Cannot encrypt content -- bad algorithm parameter!: " + e.getMessage()); } } @Override public void write(byte[] b, int off, int len) throws IOException { try { writeToNetwork(b, off, len); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } } /** * Actually write bytes to the network. * @param buf as in write(byte[], int, int) * @param offset as in write(byte[], int, int) * @param len as in write(byte[]) * @throws IOException on network errors * @throws InvalidKeyException if we cannot encrypt content as specified * @throws SignatureException if we cannot sign content * @throws NoSuchAlgorithmException if encryption requests invalid algorithm */ protected void writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { if ((len <= 0) || (null == buf) || (buf.length == 0) || (offset >= buf.length)) throw new IllegalArgumentException("Invalid argument!"); long bytesToWrite = len; // Here's an advantage of the old, complicated way -- with that, only had to allocate // as many blocks as you were going to write. while (bytesToWrite > 0) { long thisBufAvail = _buffer.length - _blockOffset; long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail; System.arraycopy(buf, (int)offset, _buffer, (int)_blockOffset, (int)toWriteNow); _dh.update(buf, (int) offset, (int)toWriteNow); // add to running digest of data bytesToWrite -= toWriteNow; // amount of data left to write in current call _blockOffset += toWriteNow; // write offset into current block buffer offset += toWriteNow; // read offset into input buffer _totalLength += toWriteNow; // increment here so we can write log entries on partial writes Log.finest("write: added " + toWriteNow + " bytes to buffer. blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block), " + _totalLength + " written."); if (_blockOffset >= _buffer.length) { // We're out of buffers. Time to flush to the network. Log.info("write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network."); flush(); // will reset _blockIndex and _blockOffset } } } /** * Flush partial hanging block if we have one. * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IOException * @throws InterruptedException */ protected void closeNetworkData() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException, InterruptedException { // flush last partial buffers. Remove previous code to specially handle // small data objects (written as single blocks without headers); instead // write them as single-fragment files. Subclasses will determine whether or not // to write a header. Log.info("closeNetworkData: final flush, wrote " + _totalLength + " bytes."); flush(true); // true means write out the partial last block, if there is one } /** * @param flushLastBlock Do we flush a partially-filled last block in the current set * of blocks? Not normally, we want to fill blocks. So if a user calls a manual * flush(), we want to flush all full blocks, but not a last partial -- readers of * this block-fragmented content (other streams make other sorts of fragments, this one * is designed for files of same block size) expect all fragments but the last to be * the same size. The only time we flush a last partial is on close(), when it is the * last block of the data. This flag, passed in only by internal methods, tells us it's * time to do that. * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws InterruptedException * @throws IOException * @throws InvalidAlgorithmParameterException */ protected void flushToNetwork(boolean flushLastBlock) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException, IOException, InvalidAlgorithmParameterException { /** * XXX - Can the blockbuffers have holes? * DKS: no. The blockCount argument to putMerkleTree is intended to tell * it how many of the blockBuffers array it should touch (are non-null). * If there are holes, there is a bigger problem. */ /** * Partial last block handling. If we are in the middle of writing a file, we only * flush complete blocks; up to _blockOffset % getBlockSize(). */ if (0 == _blockOffset) { // nothing to write return; } else if ((_blockOffset <= getBlockSize()) && (!flushLastBlock)) { // Only a single block written. We don't put out partial blocks until // close is called (or otherwise have flushLastBlock=true), so it's // easy to understand holding in that case. However, if we want to // set finalBlockID, we can't do that till we know it -- till close is // called. So we should hold off on writing the last full block as well, // until we are closed. Unfortunately that means if you call flush() // right before close(), you'll tend to sign all but the last block, // and sign that last one separately when you actually flush it. return; } if (null == _timestamp) _timestamp = CCNTime.now(); // First, are we flushing dangling blocks (e.g. on close())? If not, we always // keep at least a partial block behind. There are two reasons for this; first to // ensure we always write full blocks until the end, and second, to allow us to // mark the last block as such. So adjust the number of blocks to write // accordingly. boolean preservePartial = false; int saveBytes = 0; // Now, we have a partially or completely full buffer. Do we have a partial last block we want to preserve? // If we're not flushing, we want to save a final block (whole or partial) and move // it down. if (!flushLastBlock) { saveBytes = _blockOffset % getBlockSize(); if (0 == saveBytes) { saveBytes = getBlockSize(); // full last block, save it anyway so can mark as last. } preservePartial = true; } // otherwise saveBytes = 0, so ok // Three cases -- // 1) we have nothing to flush (0 bytes or < a single block) (handled above) // 2) we're flushing a single block and can put it out with a straight signature // 3) we're flushing more than one block, and need to use a bulk signer. // The reading/verification code will // cope just fine with a single file written in a mix of bulk and straight signature // verified blocks. if ((_blockOffset - saveBytes) <= getBlockSize()) { // Single block to write. If we get here, we are forcing a flush (see above // discussion about holding back partial or even a single full block till // forced flush/close in order to set finalBlockID). Log.info("flush: asked to put a single block to the network, are we finishing the file? " + flushLastBlock + "."); // DKS TODO -- think about types, freshness, fix markers for impending last block/first block if ((_blockOffset - saveBytes) < getBlockSize()) { Log.warning("flush(): writing hanging partial last block of file: " + (_blockOffset-saveBytes) + " bytes, block total is " + getBlockSize() + ", holding back " + saveBytes + " bytes, called by close? " + flushLastBlock); } else { Log.warning("flush(): writing single full block of file: " + _baseName + ", holding back " + saveBytes + " bytes."); } _baseNameIndex = _segmenter.putFragment(_baseName, _baseNameIndex, _buffer, 0, (_blockOffset-saveBytes), _type, _timestamp, null, (flushLastBlock ? _baseNameIndex : null), _locator, _publisher); } else { Log.info("flush: putting merkle tree to the network, baseName " + _baseName + " basenameindex " + ContentName.componentPrintURI(SegmentationProfile.getSegmentNumberNameComponent(_baseNameIndex)) + "; " + _blockOffset + " bytes written, holding back " + saveBytes + " flushing final blocks? " + flushLastBlock + "."); // Generate Merkle tree (or other auth structure) and signedInfos and put contents. // We always flush all the blocks starting from 0, so the baseBlockIndex is always 0. // DKS TODO fix last block marking _baseNameIndex = _segmenter.fragmentedPut(_baseName, _baseNameIndex, _buffer, 0, _blockOffset-saveBytes, getBlockSize(), _type, _timestamp, null, (flushLastBlock ? CCNSegmenter.LAST_SEGMENT : null), _locator, _publisher); } if (preservePartial) { System.arraycopy(_buffer, _blockOffset-saveBytes, _buffer, 0, saveBytes); _blockOffset = saveBytes; } else { _blockOffset = 0; } // zeroise unused bytes Arrays.fill(_buffer, _blockOffset, _buffer.length, (byte)0); } /** * @return number of bytes that have been written on this stream. */ protected long lengthWritten() { return _totalLength; } }
package thinwire.render.web; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.EventListener; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.logging.Logger; import java.util.logging.Level; import thinwire.render.RenderStateEvent; import thinwire.render.RenderStateListener; import thinwire.render.Renderer; import thinwire.ui.event.*; import thinwire.ui.Component; import thinwire.ui.Container; import thinwire.ui.DateBox; import thinwire.ui.GridBox; import thinwire.ui.HierarchyComponent; import thinwire.ui.Menu; import thinwire.ui.Tree; import thinwire.ui.event.PropertyChangeEvent; import thinwire.ui.style.*; /** * @author Joshua J. Gertzen */ abstract class ComponentRenderer implements Renderer, WebComponentListener { static final String SET_STYLE = "setStyle"; static final String SET_STYLES = "setStyles"; static final String REGISTER_EVENT_NOTIFIER = "registerEventNotifier"; static final String UNREGISTER_EVENT_NOTIFIER = "unregisterEventNotifier"; static final String SET_ENABLED = "setEnabled"; static final String SET_FOCUS = "setFocus"; static final String SET_FOCUS_CAPABLE = "setFocusCapable"; static final String SET_X = "setX"; static final String SET_Y = "setY"; static final String SET_WIDTH = "setWidth"; static final String SET_HEIGHT = "setHeight"; static final String SET_VISIBLE = "setVisible"; static final String SET_OPACITY = "setOpacity"; static final String SET_PROPERTY_WITH_EFFECT = "setPropertyWithEffect"; //Shared by other renderers static final String DESTROY = "destroy"; static final String SET_IMAGE = "setImage"; static final String SET_ALIGN_X = "setAlignX"; static final String CLIENT_EVENT_DROP = "drop"; static final Logger log = Logger.getLogger(ComponentRenderer.class.getName()); static final Pattern REGEX_DOUBLE_SLASH = Pattern.compile("\\\\"); static final Pattern REGEX_DOUBLE_QUOTE = Pattern.compile("\""); static final Pattern REGEX_CRLF = Pattern.compile("\\r?\\n"); static final RichTextParser RICH_TEXT_PARSER = new RichTextParser(); private static final Object NO_VALUE = new Object(); private Map<String, Object> ignoredProperties = new HashMap<String, Object>(3); private List<String> remoteFiles; private StringBuilder initProps = new StringBuilder(); private Map<String, String> clientSideProps = new HashMap<String, String>(); String jsClass; Component comp; WindowRenderer wr; ContainerRenderer cr; Integer id; void init(String jsClass, WindowRenderer wr, Component comp, ComponentRenderer container) { this.jsClass = jsClass; this.wr = wr; this.cr = container instanceof ContainerRenderer ? (ContainerRenderer)container : null; this.comp = comp; } static String getSimpleClassName(Class type) { String text = type.getName(); text = text.substring(text.lastIndexOf('.') + 1); return text; } void render(WindowRenderer wr, Component comp, ComponentRenderer container) { id = wr.addComponentId(comp); if (this instanceof WebComponentListener) wr.ai.setWebComponentListener(id, this); Effect.Motion visibleChange = comp.getStyle().getFX().getVisibleChange(); addClientSideProperty(Component.PROPERTY_FOCUS); if (!isPropertyChangeIgnored(Component.PROPERTY_X)) addInitProperty(Component.PROPERTY_X, comp.getX()); if (!isPropertyChangeIgnored(Component.PROPERTY_Y)) addInitProperty(Component.PROPERTY_Y, comp.getY()); if (!isPropertyChangeIgnored(Component.PROPERTY_WIDTH)) addInitProperty(Component.PROPERTY_WIDTH, comp.getWidth()); if (!isPropertyChangeIgnored(Component.PROPERTY_HEIGHT)) addInitProperty(Component.PROPERTY_HEIGHT, comp.getHeight()); if (!isPropertyChangeIgnored(Style.PROPERTY_OPACITY) && comp.getStyle().getOpacity() != 100) addInitProperty(Style.PROPERTY_OPACITY, comp.getStyle().getOpacity()); if (!isPropertyChangeIgnored(Component.PROPERTY_VISIBLE)) addInitProperty(Component.PROPERTY_VISIBLE, visibleChange != Effect.Motion.NONE && cr != null && cr.isFullyRendered() ? Boolean.FALSE : comp.isVisible()); if (!isPropertyChangeIgnored(Component.PROPERTY_ENABLED)) addInitProperty(Component.PROPERTY_ENABLED, comp.isEnabled()); if (!comp.isFocusCapable()) addInitProperty(Component.PROPERTY_FOCUS_CAPABLE, false); Style defaultStyle = wr.ai.getDefaultStyle(comp.getClass()); addInitProperty("styleClass", wr.ai.styleToStyleClass.get(defaultStyle)); StringBuilder styleProps = wr.ai.getStyleValues(this, new StringBuilder(), comp.getStyle(), defaultStyle); if (styleProps.length() > 0) addInitProperty("styleProps", styleProps); if (comp.isFocus()) addInitProperty(Component.PROPERTY_FOCUS, true); Object parent = comp.getParent(); if (parent instanceof Container) addInitProperty("insertAtIndex", ((Container)parent).getChildren().indexOf(comp)); if (jsClass != null) { initProps.insert(0, '{'); initProps.setCharAt(initProps.length() - 1, '}'); wr.ai.clientSideFunctionCall("tw_newComponent", jsClass, id, cr == null ? (container == null ? 0 : container.id) : cr.id, initProps); initProps = null; } if (visibleChange != Effect.Motion.NONE && !isPropertyChangeIgnored(Component.PROPERTY_VISIBLE) && comp.isVisible() && cr != null && cr.isFullyRendered()) setPropertyWithEffect(Component.PROPERTY_VISIBLE, Boolean.TRUE, Boolean.FALSE, SET_VISIBLE, FX.PROPERTY_FX_VISIBLE_CHANGE); wr.ai.setPackagePrivateMember("renderer", comp, this); if (comp.isFocusCapable() && comp.isEnabled() && ((Container)wr.comp).getComponentWithFocus() == null) comp.setFocus(true); wr.ai.flushRenderCallbacks(comp, id); } private void setStyle(String propertyName, Object oldValue) { if (propertyName.startsWith("fx") || isPropertyChangeIgnored(propertyName)) return; Style s = comp.getStyle(); if (propertyName.equals(Border.PROPERTY_BORDER_TYPE) && s.getBorder().getType() == Border.Type.IMAGE) return; Object value; if (propertyName.equals(Border.PROPERTY_BORDER_COLOR)) { if (s.getBorder().getType() == Border.Type.NONE) return; value = s.getBorder().getColor(); } else if (propertyName.equals(Border.PROPERTY_BORDER_IMAGE)) { value = s.getBorder().getImageInfo(); } else { value = s.getProperty(propertyName); } StringBuilder sb = new StringBuilder(); sb.append('{'); if (value instanceof Border.Type) { if (value == Border.Type.NONE) { value = Border.Type.SOLID; wr.ai.getStyleValue(this, sb, Border.PROPERTY_BORDER_COLOR, s.getBackground().getColor()); } else if (oldValue == Border.Type.NONE) { wr.ai.getStyleValue(this, sb, Border.PROPERTY_BORDER_COLOR, s.getBorder().getColor()); } } wr.ai.getStyleValue(this, sb, propertyName, value); sb.setCharAt(sb.length() - 1, '}'); postClientEvent(SET_STYLES, sb); } void destroy() { wr.ai.setPackagePrivateMember("renderer", comp, null); wr.ai.setWebComponentListener(id, null); comp.removePropertyChangeListener(this); wr.removeComponentId(comp); ignoredProperties.clear(); comp = null; wr = null; id = null; initProps = new StringBuilder(); ignoredProperties = new HashMap<String, Object>(3); if (remoteFiles != null) { for (String s : remoteFiles) { try { RemoteFileMap.INSTANCE.remove(s); } catch (IOException e) { log.log(Level.WARNING, "Local file no longer exists", e); } } } remoteFiles = null; } void addInitProperty(String name, Object value) { initProps.append(name).append(':'); WebApplication.encodeObject(initProps, value); initProps.append(','); } void addClientSideProperty(String name) { this.clientSideProps.put(name, name); } void addClientSideProperty(String name, String clientName) { this.clientSideProps.put(name, clientName); } public void eventSubTypeListenerInit(Class<? extends EventListener> clazz, Set<Object> subTypes) { for (Object subType : subTypes) { eventSubTypeListenerAdded(clazz, subType); } } private RenderStateListener dragRenderListener; public void eventSubTypeListenerAdded(Class<? extends EventListener> clazz, Object subType) { if (PropertyChangeListener.class.isAssignableFrom(clazz)) { String prop = clientSideProps.get(subType); if (prop != null) { if (!prop.equals(subType)) { String count = clientSideProps.get(prop); if (count == null) { clientSideProps.put(prop, "1"); postClientEvent(REGISTER_EVENT_NOTIFIER, "propertyChange", prop); } else { clientSideProps.put(prop, String.valueOf(Integer.parseInt(count) + 1)); } } else { postClientEvent(REGISTER_EVENT_NOTIFIER, "propertyChange", prop); } } } else if (ActionListener.class.isAssignableFrom(clazz)) { postClientEvent(REGISTER_EVENT_NOTIFIER, "action", subType); } else if (KeyPressListener.class.isAssignableFrom(clazz)) { postClientEvent(REGISTER_EVENT_NOTIFIER, "keyPress", subType); } else if (DropListener.class.isAssignableFrom(clazz)) { final Component dragComponent = (Component)subType; if (dragRenderListener == null) { dragRenderListener = new RenderStateListener() { public void renderStateChange(RenderStateEvent ev) { if (wr == null) { if (dragRenderListener != null) { ((WebApplication)WebApplication.current()).removeRenderStateListener(comp, dragRenderListener); dragRenderListener = null; } } else { wr.ai.clientSideMethodCall(wr.ai.getComponentId(dragComponent), "addDragTarget", id); } } }; } wr.ai.addRenderStateListener(dragComponent, dragRenderListener); } } public void eventSubTypeListenerRemoved(Class<? extends EventListener> clazz, Object subType) { if (PropertyChangeListener.class.isAssignableFrom(clazz)) { String prop = clientSideProps.get(subType); if (prop != null) { if (!prop.equals(subType)) { int cnt = Integer.parseInt(clientSideProps.get(prop)); if (cnt == 1) { clientSideProps.remove(prop); postClientEvent(UNREGISTER_EVENT_NOTIFIER, "propertyChange", prop); } else { clientSideProps.put(prop, String.valueOf(cnt - 1)); } } else { postClientEvent(UNREGISTER_EVENT_NOTIFIER, "propertyChange", prop); } } } else if (ActionListener.class.isAssignableFrom(clazz)) { postClientEvent(UNREGISTER_EVENT_NOTIFIER, "action", subType); } else if (KeyPressListener.class.isAssignableFrom(clazz)) { postClientEvent(UNREGISTER_EVENT_NOTIFIER, "keyPress", subType); } else if (DropListener.class.isAssignableFrom(clazz)) { Integer dragComponentId = wr.ai.getComponentId((Component)subType); if (dragComponentId != null) wr.ai.clientSideMethodCall(dragComponentId, "removeDragTarget", id); if (dragRenderListener != null) wr.ai.removeRenderStateListener((Component)subType, dragRenderListener); } } public int getInt(String value) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return 0; } } public void componentChange(WebComponentEvent event) { String name = event.getName(); if (name.equals(Component.ACTION_CLICK) || name.equals(Component.ACTION_DOUBLE_CLICK)) { String actionIgnoreProperty; String value = (String)event.getValue(); String[] vals = value.split(","); int x = getInt(vals[0]); int y = getInt(vals[1]); value = vals[2]; if (this.comp instanceof DateBox) { actionIgnoreProperty = DateBox.PROPERTY_SELECTED_DATE; } else if (this.comp instanceof GridBox) { actionIgnoreProperty = GridBox.Row.PROPERTY_ROW_SELECTED; } else if (comp instanceof Tree) { actionIgnoreProperty = Tree.Item.PROPERTY_ITEM_SELECTED; } else if (comp instanceof Container) { actionIgnoreProperty = null; value = ""; } else { actionIgnoreProperty = null; } if (actionIgnoreProperty != null) setPropertyChangeIgnored(actionIgnoreProperty, true); comp.fireAction(new ActionEvent(name, comp, getEventObject(comp, value), x, y, x, y)); if (actionIgnoreProperty != null) setPropertyChangeIgnored(actionIgnoreProperty, false); } else if (event.getName().equals(CLIENT_EVENT_DROP)) { String[] parts = ((String)event.getValue()).split(",", -1); Component dragComponent = (Component)wr.ai.getComponentFromId(Integer.parseInt(parts[1])); int dragComponentX = getInt(parts[3]); int dragComponentY = getInt(parts[4]); int sourceComponentX = getInt(parts[5]); int sourceComponentY = getInt(parts[6]); comp.fireDrop(new DropEvent(comp, getEventObject(comp, parts[0]), sourceComponentX, sourceComponentY, sourceComponentX, sourceComponentY, dragComponent, getEventObject(dragComponent, parts[2]), dragComponentX, dragComponentY, dragComponentX, dragComponentY)); } else if (name.equals("size")) { this.setPropertyChangeIgnored(Component.PROPERTY_WIDTH, true); this.setPropertyChangeIgnored(Component.PROPERTY_HEIGHT, true); String[] args = ((String)event.getValue()).split(","); comp.setSize(Integer.valueOf(args[0]), Integer.valueOf(args[1])); this.setPropertyChangeIgnored(Component.PROPERTY_WIDTH, false); this.setPropertyChangeIgnored(Component.PROPERTY_HEIGHT, false); } else if (name.equals("position")) { this.setPropertyChangeIgnored(Component.PROPERTY_X, true); this.setPropertyChangeIgnored(Component.PROPERTY_Y, true); String[] args = ((String)event.getValue()).split(","); comp.setPosition(Integer.valueOf(args[0]), Integer.valueOf(args[1])); this.setPropertyChangeIgnored(Component.PROPERTY_X, false); this.setPropertyChangeIgnored(Component.PROPERTY_Y, false); } else if (name.equals("bounds")) { this.setPropertyChangeIgnored(Component.PROPERTY_X, true); this.setPropertyChangeIgnored(Component.PROPERTY_Y, true); this.setPropertyChangeIgnored(Component.PROPERTY_WIDTH, true); this.setPropertyChangeIgnored(Component.PROPERTY_HEIGHT, true); String[] args = ((String)event.getValue()).split(","); comp.setBounds(Integer.valueOf(args[0]), Integer.valueOf(args[1]), Integer.valueOf(args[2]), Integer.valueOf(args[3])); this.setPropertyChangeIgnored(Component.PROPERTY_WIDTH, false); this.setPropertyChangeIgnored(Component.PROPERTY_HEIGHT, false); this.setPropertyChangeIgnored(Component.PROPERTY_X, false); this.setPropertyChangeIgnored(Component.PROPERTY_Y, false); } else if (name.equals(Component.PROPERTY_VISIBLE)) { this.setPropertyChangeIgnored(Component.PROPERTY_VISIBLE, true); comp.setVisible(((String)event.getValue()).toLowerCase().equals("true")); this.setPropertyChangeIgnored(Component.PROPERTY_VISIBLE, false); } else if (name.equals(Component.PROPERTY_FOCUS)) { setPropertyChangeIgnored(Component.PROPERTY_FOCUS, true); ContainerRenderer cr = this.cr; while (cr != null) { cr.setPropertyChangeIgnored(Component.PROPERTY_FOCUS, true); cr = cr.cr; } comp.setFocus(Boolean.valueOf((String)event.getValue()).booleanValue()); cr = this.cr; while (cr != null) { cr.setPropertyChangeIgnored(Component.PROPERTY_FOCUS, false); cr = cr.cr; } setPropertyChangeIgnored(Component.PROPERTY_FOCUS, false); } else if (name.equals("keyPress")) { comp.fireKeyPress(new KeyPressEvent((String)event.getValue(), comp)); } } void setPropertyWithEffect(String propertyName, Object newValue, Object oldValue, String standardMethod, String styleProp) { Effect.Motion type; FX fx = comp.getStyle().getFX(); if (styleProp.equals(FX.PROPERTY_FX_VISIBLE_CHANGE)) { type = fx.getVisibleChange(); } else if (styleProp.equals(FX.PROPERTY_FX_OPACITY_CHANGE)) { type = fx.getOpacityChange(); } else if (styleProp.equals(FX.PROPERTY_FX_POSITION_CHANGE)) { type = fx.getPositionChange(); } else if (styleProp.equals(FX.PROPERTY_FX_SIZE_CHANGE)) { type = fx.getSizeChange(); } else { type = fx.getColorChange(); } Effect.Motion NONE = Effect.Motion.NONE; if (type == NONE || (type.getDuration() == NONE.getDuration()) && type.getFrames() == NONE.getFrames()) { postClientEvent(standardMethod, newValue); } else { int time = type.getDuration(); StringBuffer seq = new StringBuffer(); Effect.Transition trans = type.getTransition(); int steps = (int)Math.floor(time / type.getFrames() + .5) - 1; double step = Math.floor(1.0 / steps * 100000) / 100000; //percent of each step; if (styleProp.equals(FX.PROPERTY_FX_COLOR_CHANGE)) { Color prev = (Color)oldValue; if (prev.isSystemColor()) prev = wr.ai.systemColors.get(prev.toString()); Color next = (Color)newValue; if (next.isSystemColor()) next = wr.ai.systemColors.get(next.toString()); if (prev == null || next == null) { postClientEvent(standardMethod, newValue); } else { int rChange = next.getRed() - prev.getRed(); if (rChange < 0) rChange = ~rChange + 1; int gChange = next.getGreen() - prev.getGreen(); if (gChange < 0) gChange = ~gChange + 1; int bChange = next.getBlue() - prev.getBlue(); if (bChange < 0) bChange = ~bChange + 1; seq.append('['); for (int i = 1; i <= steps; i++) { int rSize = (int)Math.floor(trans.apply(step * i) * rChange); rSize = next.getRed() < prev.getRed() ? prev.getRed() - rSize : prev.getRed() + rSize; int gSize = (int)Math.floor(trans.apply(step * i) * gChange); gSize = next.getGreen() < prev.getGreen() ? prev.getGreen() - gSize : prev.getGreen() + gSize; int bSize = (int)Math.floor(trans.apply(step * i) * bChange); bSize = next.getBlue() < prev.getBlue() ? prev.getBlue() - bSize : prev.getBlue() + bSize; seq.append("\"rgb(").append(rSize).append(',').append(gSize).append(',').append(bSize).append(")\"").append(','); } seq.append('"').append(next.toRGBString()).append('"').append(']'); wr.ai.clientSideMethodCall(id, SET_PROPERTY_WITH_EFFECT, propertyName, time, seq); } } else { int prev, next; if (styleProp.equals(FX.PROPERTY_FX_VISIBLE_CHANGE)) { propertyName = "opacity"; int opacity = comp.getStyle().getOpacity(); prev = ((Boolean)oldValue).booleanValue() ? opacity : 0; next = ((Boolean)newValue).booleanValue() ? opacity : 0; } else { prev = (Integer)oldValue; next = (Integer)newValue; } int change = next - prev; if (change < 0) change = ~change + 1; seq.append('['); for (int i = 1; i <= steps; i++) { int size = (int)Math.floor(trans.apply(step * i) * change); seq.append(next < prev ? prev - size : prev + size).append(','); } seq.append(next).append(']'); wr.ai.clientSideMethodCall(id, SET_PROPERTY_WITH_EFFECT, propertyName, time, seq); } } } public void propertyChange(PropertyChangeEvent pce) { String name = pce.getPropertyName(); if (isPropertyChangeIgnored(name)) return; if (name.equals(Component.PROPERTY_ENABLED)) { postClientEvent(SET_ENABLED, pce.getNewValue()); } else if (name.equals(Component.PROPERTY_FOCUS)) { Object newValue = pce.getNewValue(); if (((Boolean)newValue).booleanValue()) postClientEvent(SET_FOCUS, newValue); } else if (name.equals(Component.PROPERTY_FOCUS_CAPABLE)) { postClientEvent(SET_FOCUS_CAPABLE, pce.getNewValue()); } else if (name.equals(Background.PROPERTY_BACKGROUND_COLOR) || name.equals(Border.PROPERTY_BORDER_COLOR) || name.equals(Font.PROPERTY_FONT_COLOR)) { String setMethod = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), setMethod, FX.PROPERTY_FX_COLOR_CHANGE); } else if (name.equals(Style.PROPERTY_OPACITY)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_OPACITY, FX.PROPERTY_FX_OPACITY_CHANGE); } else if (name.equals(Component.PROPERTY_X)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_X, FX.PROPERTY_FX_POSITION_CHANGE); } else if (name.equals(Component.PROPERTY_Y)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_Y, FX.PROPERTY_FX_POSITION_CHANGE); } else if (name.equals(Component.PROPERTY_WIDTH)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_WIDTH, FX.PROPERTY_FX_SIZE_CHANGE); } else if (name.equals(Component.PROPERTY_HEIGHT)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_HEIGHT, FX.PROPERTY_FX_SIZE_CHANGE); } else if (name.equals(Component.PROPERTY_VISIBLE)) { setPropertyWithEffect(name, pce.getNewValue(), pce.getOldValue(), SET_VISIBLE, FX.PROPERTY_FX_VISIBLE_CHANGE); } else { Object source = pce.getSource(); if (source instanceof Background || source instanceof Font || source instanceof Border) setStyle(pce.getPropertyName(), pce.getOldValue()); } } final void postClientEvent(String methodName, Object... args) { wr.ai.clientSideMethodCall(id, methodName, args); } final void setPropertyChangeIgnored(String name, boolean ignore) { if (ignore) { ignoredProperties.put(name, NO_VALUE); } else { ignoredProperties.remove(name); } } final boolean isPropertyChangeIgnored(String name, Object value) { if (ignoredProperties.containsKey(name)) { if (value == NO_VALUE) { return true; } else { Object ignoredValue = ignoredProperties.get(name); return ignoredValue == value || (ignoredValue != null && ignoredValue.equals(value)); } } else { return false; } } final boolean isPropertyChangeIgnored(String name) { return isPropertyChangeIgnored(name, NO_VALUE); } final boolean resetPropertyChangeIgnored(String name, Object value) { boolean ret = isPropertyChangeIgnored(name, value); if (ret) ignoredProperties.remove(name); return ret; } final boolean resetPropertyChangeIgnored(String name) { return resetPropertyChangeIgnored(name, NO_VALUE); } static final String getEscapedText(String s) { s = REGEX_DOUBLE_SLASH.matcher(s).replaceAll("\\\\\\\\"); s = REGEX_DOUBLE_QUOTE.matcher(s).replaceAll("\\\\\""); s = REGEX_CRLF.matcher(s).replaceAll(" "); return s; } static Object getEventObject(Component comp, String data) { Object o; if (comp instanceof GridBox) { String[] values = data.split("@"); o = new GridBox.Range((GridBox)comp, Integer.parseInt(values[0]), Integer.parseInt(values[1])); } else if (comp instanceof Tree || comp instanceof Menu) { o = TreeRenderer.fullIndexItem((HierarchyComponent)comp, data); } else if (comp instanceof DateBox) { try { o = DateBoxRenderer.dateBoxFormat.parse(data); } catch (Exception e) { throw new RuntimeException(e); } } else { o = null; } return o; } final String getQualifiedURL(String location) { if (location.trim().length() > 0) { URI uri; WindowRenderer wr = this instanceof WindowRenderer ? (WindowRenderer)this : this.wr; if (location.startsWith("file") || location.startsWith("class") || wr.ai.getRelativeFile(location).exists()) { if (!location.startsWith("class")) location = wr.ai.getRelativeFile(location).getAbsolutePath(); if (remoteFiles == null) remoteFiles = new ArrayList<String>(5); remoteFiles.add(location); location = "%SYSROOT%" + RemoteFileMap.INSTANCE.add(location); } else { try { location = new URI(location).toString(); } catch (URISyntaxException e) { } } } else { location = ""; } return location; } }
package com.axelor.apps.account.web; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.SubrogationRelease; import com.axelor.apps.account.db.repo.SubrogationReleaseRepository; import com.axelor.apps.account.service.SubrogationReleaseService; import com.axelor.apps.base.db.Company; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; import com.axelor.meta.schema.actions.ActionView; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.util.List; @Singleton public class SubrogationReleaseController { private SubrogationReleaseService subrogationReleaseService; @Inject public SubrogationReleaseController(SubrogationReleaseService subrogationReleaseService) { this.subrogationReleaseService = subrogationReleaseService; } public void retrieveInvoices(ActionRequest request, ActionResponse response) { try { SubrogationRelease subrogationRelease = request.getContext().asType(SubrogationRelease.class); Company company = subrogationRelease.getCompany(); List<Invoice> invoiceList = subrogationReleaseService.retrieveInvoices(company); response.setValue("invoiceSet", invoiceList); } catch (Exception e) { response.setError(e.getMessage()); TraceBackService.trace(e); } } public void transmitRelease(ActionRequest request, ActionResponse response) { try { SubrogationRelease subrogationRelease = request.getContext().asType(SubrogationRelease.class); subrogationRelease = Beans.get(SubrogationReleaseRepository.class).find(subrogationRelease.getId()); subrogationReleaseService.transmitRelease(subrogationRelease); response.setReload(true); } catch (Exception e) { response.setError(e.getMessage()); TraceBackService.trace(e); } } public void printToPDF(ActionRequest request, ActionResponse response) throws AxelorException { try { SubrogationRelease subrogationRelease = request.getContext().asType(SubrogationRelease.class); String name = String.format( "%s %s", I18n.get("Subrogation release"), subrogationRelease.getSequenceNumber()); String fileLink = subrogationReleaseService.printToPDF(subrogationRelease, name); response.setView(ActionView.define(name).add("html", fileLink).map()); response.setReload(true); } catch (Exception e) { response.setError(e.getMessage()); TraceBackService.trace(e); } } public void exportToCSV(ActionRequest request, ActionResponse response) throws AxelorException, IOException { try { SubrogationRelease subrogationRelease = request.getContext().asType(SubrogationRelease.class); subrogationReleaseService.exportToCSV(subrogationRelease); response.setReload(true); } catch (Exception e) { response.setError(e.getMessage()); TraceBackService.trace(e); } } public void enterReleaseInTheAccounts(ActionRequest request, ActionResponse response) throws AxelorException { try { SubrogationRelease subrogationRelease = request.getContext().asType(SubrogationRelease.class); subrogationRelease = Beans.get(SubrogationReleaseRepository.class).find(subrogationRelease.getId()); subrogationReleaseService.enterReleaseInTheAccounts(subrogationRelease); response.setReload(true); } catch (Exception e) { response.setError(e.getMessage()); TraceBackService.trace(e); } } }
package org.ovirt.engine.core.bll; import java.io.File; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.validator.LocalizedVmStatus; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.utils.ValidationUtils; import org.ovirt.engine.core.common.vdscommands.ChangeDiskVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; public class ChangeDiskCommand<T extends ChangeDiskCommandParameters> extends VmOperationCommandBase<T> { private String cdImagePath; public ChangeDiskCommand(T parameters) { super(parameters); } public String getDiskName() { return new File(cdImagePath).getName(); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CHANGE_CD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } @Override protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (!canRunActionOnNonManagedVm()) { return false; } cdImagePath = getParameters().getCdImagePath(); if (!getVm().isRunningOrPaused()) { addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); // An empty 'cdImagePath' means eject CD if (!StringUtils.isEmpty(cdImagePath)) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CHANGE_CD); } else { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__EJECT_CD); } return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(getVm().getStatus())); } if ((IsoDomainListSyncronizer.getInstance().findActiveISODomain(getVm().getStoragePoolId()) == null) && !StringUtils.isEmpty(cdImagePath)) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CHANGE_CD); return failCanDoAction(VdcBllMessages.VM_CANNOT_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO); } if (StringUtils.isNotEmpty(cdImagePath) && !cdImagePath.endsWith(ValidationUtils.ISO_SUFFIX)) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CHANGE_CD); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_CDROM_DISK_FORMAT); } return true; } @Override protected void perform() { cdImagePath = ImagesHandler.cdPathWindowsToLinux(getParameters().getCdImagePath(), getVm().getStoragePoolId(), getVm().getRunOnVds()); setActionReturnValue(runVdsCommand(VDSCommandType.ChangeDisk, new ChangeDiskVDSCommandParameters(getVdsId(), getVm().getId(), cdImagePath)) .getReturnValue()); VmHandler.updateCurrentCd(getVdsId(), getVm(), getParameters().getCdImagePath()); setSucceeded(true); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? "".equals(cdImagePath) ? AuditLogType.USER_EJECT_VM_DISK : AuditLogType.USER_CHANGE_DISK_VM : AuditLogType.USER_FAILED_CHANGE_DISK_VM; } }
package org.ovirt.engine.core.bll; import static junit.framework.Assert.assertNotSame; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import java.lang.reflect.Constructor; import java.lang.reflect.ParameterizedType; import org.junit.Before; import org.junit.Test; import org.ovirt.engine.core.common.queries.VdcQueryParametersBase; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public abstract class AbstractQueryTest<P extends VdcQueryParametersBase, Q extends QueriesCommandBase<? extends P>> { protected P params; private Q query; /** Sets up a mock user a spy query with it, and the generic query parameters */ @Before public void setUp() throws Exception { setUpMockQueryParameters(); setUpSpyQuery(); } /** Sets up a mock for {@link #params} */ private void setUpMockQueryParameters() { params = mock(getParameterType()); } /** Sets up a mock for {@link #query} */ protected void setUpSpyQuery() throws Exception { setUpSpyQuery(getQueryParameters()); } protected Q setUpSpyQuery(P parameters) throws Exception { Constructor<? extends Q> con = getQueryType().getConstructor(getParameterType()); query = spy(con.newInstance(parameters)); DbFacade dbFacadeMock = mock(DbFacade.class); doReturn(dbFacadeMock).when(query).getDbFacade(); return query; } /** Extract the {@link Class} object for the P generic parameter */ @SuppressWarnings("unchecked") protected Class<? extends P> getParameterType() { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); return (Class<? extends P>) parameterizedType.getActualTypeArguments()[0]; } /** Extract the {@link Class} object for the Q generic parameter */ @SuppressWarnings("unchecked") protected Class<? extends Q> getQueryType() { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); ParameterizedType queryParameterizedType = (ParameterizedType) parameterizedType.getActualTypeArguments()[1]; return (Class<? extends Q>) queryParameterizedType.getRawType(); } /** Power-Mocks {@link DbFacade#getInstance()} and returns a mock for it */ protected DbFacade getDbFacadeMockInstance() { return getQuery().getDbFacade(); } /** @return The spied query to use in the test */ protected Q getQuery() { return query; } /** @return The mock query parameters to use in the test */ protected P getQueryParameters() { return params; } @Test public void testQueryType() throws IllegalArgumentException, IllegalAccessException { assertNotSame("The query can't be found in the enum VdcQueryType", VdcQueryType.Unknown, TestHelperQueriesCommandType.getQueryTypeFieldValue(query)); } }
package org.intermine.bio.dataconversion; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Map.Entry; import org.intermine.bio.chado.config.ConfigAction; import org.intermine.bio.chado.config.CreateCollectionAction; import org.intermine.bio.chado.config.CreateSynonymAction; import org.intermine.bio.chado.config.DoNothingAction; import org.intermine.bio.chado.config.SetFieldConfigAction; import org.intermine.bio.util.OrganismData; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.MetaDataException; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.intermine.util.XmlUtil; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.flymine.model.genomic.LocatedSequenceFeature; import org.flymine.model.genomic.Transcript; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * A processor for the chado sequence module. * @author Kim Rutherford */ public class ChadoSequenceProcessor extends ChadoProcessor { // incremented each time we make a new ChadoSequenceProcessor to make sure we have a unique // name for temporary tables private static int tempTableCount = 0; private static final Logger LOG = Logger.getLogger(ChadoSequenceProcessor.class); // a map from chado feature id to FeatureData objects, prpulated by processFeatureTable() // and used to get object types, Item IDs etc. (see FeatureData) private Map<Integer, FeatureData> featureMap = new HashMap<Integer, FeatureData>(); // we don't configure anything by default, so the process methods do their default actions private static final MultiKeyMap DEFAULT_CONFIG = new MultiKeyMap(); // A map from chromosome uniqueName to chado feature_ids, populated by processFeatureTable() private Map<Integer, Map<String, Integer>> chromosomeMaps = new HashMap<Integer, Map<String, Integer>>(); // a map from chado pubmed id to item identifier for the publication private Map<Integer, String> publications = new HashMap<Integer, String>(); // the name of the temporary table we create from the feature table to speed up processing private String tempFeatureTableName = null; // a list of the possible names for the part_of relation private static final List<String> PARTOF_RELATIONS = Arrays.asList("partof", "part_of"); // default feature types to query from the feature table private static final List<String> DEFAULT_FEATURES = Arrays.asList( "gene", "mRNA", "transcript", "CDS", "intron", "exon", "EST", "five_prime_untranslated_region", "five_prime_UTR", "three_prime_untranslated_region", "three_prime_UTR", "origin_of_replication" ); // default chromosome-like feature types - ie those types of features that occur in the // srcfeature column of the featureloc table private static final List<String> DEFAULT_CHROMOSOME_FEATURES = Arrays.asList("chromosome", "chromosome_arm", "ultra_scaffold", "golden_path_region"); /** * An action that makes a synonym. */ protected static final ConfigAction CREATE_SYNONYM_ACTION = new CreateSynonymAction(); /** * An action that does nothing - used to ignore a synonym/dbxref/whatever instead of doing the * default. */ protected static final ConfigAction DO_NOTHING_ACTION = new DoNothingAction(); // the prefix to use when making a temporary table, the tempTableCount will be added to make it // unique private static final String TEMP_FEATURE_TABLE_NAME_PREFIX = "intermine_chado_features_temp"; // map used by processFeatureCVTermTable() to make sure the singletons objects (eg. those of private final MultiKeyMap singletonMap = new MultiKeyMap(); /** * Create a new ChadoSequenceProcessor * @param chadoDBConverter the ChadoDBConverter that is controlling this processor */ public ChadoSequenceProcessor(ChadoDBConverter chadoDBConverter) { super(chadoDBConverter); synchronized (this) { tempTableCount++; tempFeatureTableName = TEMP_FEATURE_TABLE_NAME_PREFIX + "_" + tempTableCount; } } /** * Return the config Map. * @param taxonId return the configuration for this organism * @return the Map from configuration key to a list of actions */ @SuppressWarnings("unchecked") protected Map<MultiKey, List<ConfigAction>> getConfig(int taxonId) { return DEFAULT_CONFIG; } /** * {@inheritDoc} * We process the chado database by reading each table in turn (feature, pub, featureloc, etc.) * Each row of each table is read and stored if appropriate. */ @Override public void process(Connection connection) throws Exception { // overridden by subclasses if necessary earlyExtraProcessing(connection); createFeatureTempTable(connection); processFeatureTable(connection); processFeatureCVTermTable(connection); processPubTable(connection); // process direct locations ResultSet directLocRes = getFeatureLocResultSet(connection); // we don't call getFeatureLocResultSet() in the processLocationTable() method because // processLocationTable() is called by subclasses to create locations processLocationTable(connection, directLocRes); processRelationTable(connection); processDbxrefTable(connection); processSynonymTable(connection); processFeaturePropTable(connection); // overridden by subclasses if necessary extraProcessing(connection, featureMap); // overridden by subclasses if necessary finishedProcessing(connection, featureMap); } /** * Query the feature table and store features as object of the appropriate type in the * object store. * @param connection * @throws SQLException * @throws ObjectStoreException */ // private void processFeatureTable(Connection connection) // throws SQLException, ObjectStoreException { // Set<String> chromosomeFeatureTypesSet = new HashSet<String>(getChromosomeFeatureTypes()); // ResultSet res = getFeatureResultSet(connection); // int count = 0; // while (res.next()) { // Integer featureId = new Integer(res.getInt("feature_id")); // String name = res.getString("name"); // String uniqueName = res.getString("uniquename"); // String type = res.getString("type"); // String residues = res.getString("residues"); // Integer organismId = new Integer(res.getInt("organism_id")); // if (chromosomeFeatureTypesSet.contains(type)) { // addToChromosomeMaps(organismId, uniqueName, featureId); // int seqlen = 0; // if (res.getObject("seqlen") != null) { // seqlen = res.getInt("seqlen"); // List<String> primaryIds = new ArrayList<String>(); // primaryIds.add(uniqueName); // String interMineType = TypeUtil.javaiseClassName(fixFeatureType(type)); // uniqueName = fixIdentifier(interMineType, uniqueName); // OrganismData organismData = // getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId); // Item feature = makeFeature(featureId, type, interMineType, name, uniqueName, seqlen, // organismData.getTaxonId()); // if (feature != null) { // processAndStoreFeature(feature, featureId, uniqueName, name, seqlen, residues, // interMineType, organismId); // count++; // LOG.info("created " + count + " features"); // res.close(); private void processFeatureTable(Connection connection) throws SQLException, ObjectStoreException { Set<String> chromosomeFeatureTypesSet = new HashSet<String>(getChromosomeFeatureTypes()); ResultSet res = getFeatureResultSet(connection); int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String name = res.getString("name"); String uniqueName = res.getString("uniquename"); String type = res.getString("type"); String residues = res.getString("residues"); Integer organismId = new Integer(res.getInt("organism_id")); if (chromosomeFeatureTypesSet.contains(type)) { addToChromosomeMaps(organismId, uniqueName, featureId); } int seqlen = 0; if (res.getObject("seqlen") != null) { seqlen = res.getInt("seqlen"); } List<String> primaryIds = new ArrayList<String>(); primaryIds.add(uniqueName); // if (feature != null) { // processAndStoreFeature(feature, featureId, uniqueName, name, seqlen, residues, // interMineType, organismId); processAndStoreFeature(featureId, uniqueName, name, seqlen, residues, type, organismId); count++; } LOG.info("created " + count + " features"); res.close(); } /** * Add the given chromosome feature_id, uniqueName and organismId to chromosomeMaps. */ private void addToChromosomeMaps(Integer organismId, String chrUniqueName, Integer chrId) { Map<String, Integer> chromosomeMap; if (chromosomeMaps.containsKey(organismId)) { chromosomeMap = chromosomeMaps.get(organismId); } else { chromosomeMap = new HashMap<String, Integer>(); chromosomeMaps.put(organismId, chromosomeMap); } chromosomeMap.put(chrUniqueName, chrId); } /** * Create and store a new InterMineObject given data from a row of the feature table in a * Chado database. * @param uniqueName the uniquename from Chado * @param name the name from Chado * @param seqlen the sequence length from Chado * @param residues the residues from Chado * @param interMineType the genomic model class name to use for the new feature * @param organismId the chado organism id * @throws ObjectStoreException if there is a problem while storing */ // private void processAndStoreFeature(Item feature, Integer featureId, String uniqueName, // String name, int seqlen, String residues, // String interMineType, Integer organismId) private void processAndStoreFeature(Integer featureId, String uniqueName, String name, int seqlen, String residues, String type, Integer organismId) throws ObjectStoreException { String interMineType = TypeUtil.javaiseClassName(fixFeatureType(type)); uniqueName = fixIdentifier(interMineType, uniqueName); OrganismData organismData = getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId); Item feature = makeFeature(featureId, type, interMineType, name, uniqueName, seqlen, organismData.getTaxonId()); organismData = getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId); int taxonId = organismData.getTaxonId(); Item organismItem = getChadoDBConverter().getOrganismItem(taxonId); FeatureData fdat = new FeatureData(); fdat.itemIdentifier = feature.getIdentifier(); fdat.uniqueName = uniqueName; fdat.chadoFeatureName = name; fdat.interMineType = XmlUtil.getFragmentFromURI(feature.getClassName()); fdat.organismData = organismData; feature.setReference("organism", organismItem); if (seqlen > 0) { feature.setAttribute("length", String.valueOf(seqlen)); fdat.setFlag(FeatureData.LENGTH_SET, true); } ChadoDBConverter chadoDBConverter = getChadoDBConverter(); String dataSourceName = chadoDBConverter.getDataSourceName(); MultiKey nameKey = new MultiKey("feature", fdat.interMineType, dataSourceName, "name"); List<ConfigAction> nameActionList = getConfig(taxonId).get(nameKey); Set<String> fieldValuesSet = new HashSet<String>(); if (!StringUtils.isBlank(name)) { String fixedName = fixIdentifier(interMineType, name); if (nameActionList == null || nameActionList.size() == 0) { if (feature.checkAttribute("symbol")) { fieldValuesSet.add(fixedName); feature.setAttribute("symbol", fixedName); } else { if (feature.checkAttribute("secondaryIdentifier")) { fieldValuesSet.add(fixedName); feature.setAttribute("secondaryIdentifier", fixedName); } else { // do nothing, if the name needs to go in a different attribute // it will need to be configured } } } else { for (ConfigAction action: nameActionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction attrAction = (SetFieldConfigAction) action; if (attrAction.isValidValue(fixedName)) { String newFieldValue = attrAction.processValue(fixedName); feature.setAttribute(attrAction.getFieldName(), newFieldValue); fieldValuesSet.add(newFieldValue); if (attrAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } } } } MultiKey uniqueNameKey = new MultiKey("feature", fdat.interMineType, dataSourceName, "uniquename"); List<ConfigAction> uniqueNameActionList = getConfig(taxonId).get(uniqueNameKey); if (uniqueNameActionList == null || uniqueNameActionList.size() == 0) { feature.setAttribute("primaryIdentifier", uniqueName); fieldValuesSet.add(uniqueName); } else { for (ConfigAction action: uniqueNameActionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction attrAction = (SetFieldConfigAction) action; if (attrAction.isValidValue(uniqueName)) { String newFieldValue = attrAction.processValue(uniqueName); feature.setAttribute(attrAction.getFieldName(), newFieldValue); fieldValuesSet.add(newFieldValue); if (attrAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } } } if (feature.canHaveReference("sequence") && residues != null && residues.length() > 0) { Item sequence = getChadoDBConverter().createItem("Sequence"); sequence.setAttribute("residues", residues); sequence.setAttribute("length", String.valueOf(seqlen)); feature.setReference("sequence", sequence); getChadoDBConverter().store(sequence); } // don't set the evidence collection - that's done by processPubTable() fdat.intermineObjectId = store(feature, taxonId); // Stores Feature // always create a synonym for the uniquename boolean uniqueNameSet = false; if (fieldValuesSet.contains(uniqueName)) { uniqueNameSet = true; } Item uniqueNameSynonym = createSynonym(fdat, "identifier", uniqueName, uniqueNameSet, null); getChadoDBConverter().store(uniqueNameSynonym); if (!StringUtils.isBlank(name)) { String fixedName = fixIdentifier(interMineType, name); if (nameActionList == null || nameActionList.size() == 0) { nameActionList = new ArrayList<ConfigAction>(); nameActionList.add(new CreateSynonymAction()); } for (ConfigAction action : nameActionList) { if (action instanceof CreateSynonymAction) { CreateSynonymAction createSynonymAction = (CreateSynonymAction) action; if (createSynonymAction.isValidValue(fixedName)) { String processedName = createSynonymAction.processValue(fixedName); if (!fdat.existingSynonyms.contains(processedName)) { boolean nameSet = fieldValuesSet.contains(processedName); Item nameSynonym = createSynonym(fdat, "name", processedName, nameSet, null); getChadoDBConverter().store(nameSynonym); } } } } } featureMap.put(featureId, fdat); } // private void processAndStoreFeature(Item feature, Integer featureId, String uniqueName, // String name, int seqlen, String residues, // String interMineType, Integer organismId) //throws ObjectStoreException { //OrganismData organismData = getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId); //int taxonId = organismData.getTaxonId(); //Item organismItem = getChadoDBConverter().getOrganismItem(taxonId); //FeatureData fdat = new FeatureData(); //fdat.itemIdentifier = feature.getIdentifier(); //fdat.uniqueName = uniqueName; //fdat.chadoFeatureName = name; //fdat.interMineType = XmlUtil.getFragmentFromURI(feature.getClassName()); //fdat.organismData = organismData; //feature.setReference("organism", organismItem); //if (seqlen > 0) { //feature.setAttribute("length", String.valueOf(seqlen)); //fdat.setFlag(FeatureData.LENGTH_SET, true); //ChadoDBConverter chadoDBConverter = getChadoDBConverter(); //String dataSourceName = chadoDBConverter.getDataSourceName(); //MultiKey nameKey = new MultiKey("feature", fdat.interMineType, dataSourceName, "name"); //List<ConfigAction> nameActionList = getConfig(taxonId).get(nameKey); //Set<String> fieldValuesSet = new HashSet<String>(); //if (!StringUtils.isBlank(name)) { //String fixedName = fixIdentifier(interMineType, name); //if (nameActionList == null || nameActionList.size() == 0) { //if (feature.checkAttribute("symbol")) { //fieldValuesSet.add(fixedName); //feature.setAttribute("symbol", fixedName); //} else { //if (feature.checkAttribute("secondaryIdentifier")) { //fieldValuesSet.add(fixedName); //feature.setAttribute("secondaryIdentifier", fixedName); //} else { //// do nothing, if the name needs to go in a different attribute //// it will need to be configured //} else { //for (ConfigAction action: nameActionList) { //if (action instanceof SetFieldConfigAction) { //SetFieldConfigAction attrAction = //(SetFieldConfigAction) action; //if (attrAction.isValidValue(fixedName)) { //String newFieldValue = attrAction.processValue(fixedName); //feature.setAttribute(attrAction.getFieldName(), newFieldValue); //fieldValuesSet.add(newFieldValue); //if (attrAction.getFieldName().equals("primaryIdentifier")) { // fdat.setFlag(FeatureData.IDENTIFIER_SET, true); //MultiKey uniqueNameKey = //new MultiKey("feature", fdat.interMineType, dataSourceName, //"uniquename"); //List<ConfigAction> uniqueNameActionList = //getConfig(taxonId).get(uniqueNameKey); //if (uniqueNameActionList == null || uniqueNameActionList.size() == 0) { //feature.setAttribute("primaryIdentifier", uniqueName); //fieldValuesSet.add(uniqueName); //} else { //for (ConfigAction action: uniqueNameActionList) { //if (action instanceof SetFieldConfigAction) { //SetFieldConfigAction attrAction = (SetFieldConfigAction) action; //if (attrAction.isValidValue(uniqueName)) { //String newFieldValue = attrAction.processValue(uniqueName); //feature.setAttribute(attrAction.getFieldName(), newFieldValue); //fieldValuesSet.add(newFieldValue); //if (attrAction.getFieldName().equals("primaryIdentifier")) { //fdat.setFlag(FeatureData.IDENTIFIER_SET, true); //if (feature.canHaveReference("sequence") && residues != null && residues.length() > 0) { //Item sequence = getChadoDBConverter().createItem("Sequence"); //sequence.setAttribute("residues", residues); //sequence.setAttribute("length", String.valueOf(seqlen)); //feature.setReference("sequence", sequence); //getChadoDBConverter().store(sequence); //// don't set the evidence collection - that's done by processPubTable() //fdat.intermineObjectId = store(feature, taxonId); // Stores Feature //// always create a synonym for the uniquename //boolean uniqueNameSet = false; //if (fieldValuesSet.contains(uniqueName)) { //uniqueNameSet = true; //Item uniqueNameSynonym = //createSynonym(fdat, "identifier", uniqueName, uniqueNameSet, null); //getChadoDBConverter().store(uniqueNameSynonym); //if (!StringUtils.isBlank(name)) { //String fixedName = fixIdentifier(interMineType, name); //if (nameActionList == null || nameActionList.size() == 0) { //nameActionList = new ArrayList<ConfigAction>(); //nameActionList.add(new CreateSynonymAction()); //for (ConfigAction action : nameActionList) { //if (action instanceof CreateSynonymAction) { //CreateSynonymAction createSynonymAction = (CreateSynonymAction) action; //if (createSynonymAction.isValidValue(fixedName)) { //String processedName = createSynonymAction.processValue(fixedName); //if (!fdat.existingSynonyms.contains(processedName)) { //boolean nameSet = fieldValuesSet.contains(processedName); //Item nameSynonym = // createSynonym(fdat, "name", processedName, nameSet, null); //getChadoDBConverter().store(nameSynonym); //featureMap.put(featureId, fdat); /** * Store the feature Item. * @param feature the Item * @param taxonId the taxon id of this feature * @return the database id of the new Item * @throws ObjectStoreException if an error occurs while storing */ protected Integer store(Item feature, int taxonId) throws ObjectStoreException { return getChadoDBConverter().store(feature); } /** * Make a new feature * @param featureId the chado feature id * @param chadoFeatureType the chado feature type (a SO term) * @param interMineType the InterMine type of the feature * @param name the name * @param uniqueName the uniquename * @param seqlen the sequence length (if known) * @param taxonId the NCBI taxon id of the current feature * @return the new feature */ protected Item makeFeature(Integer featureId, String chadoFeatureType, String interMineType, String name, String uniqueName, int seqlen, int taxonId) { return getChadoDBConverter().createItem(interMineType); } /** * Get a list of the chado/so types of the LocatedSequenceFeatures we wish to load. The list * will not include chromosome-like features (eg. "chromosome" and "chromosome_arm"). The * process methods will ignore features that are not in this list. * @return the list of features */ protected List<String> getFeatures() { return DEFAULT_FEATURES; } /** * Get a list of the chado/so types of the Chromosome-like objects we wish to load. * (eg. "chromosome" and "chromosome_arm"). * @return the list of features */ protected List<String> getChromosomeFeatureTypes() { return DEFAULT_CHROMOSOME_FEATURES; } /** * Return a list of types where one logical feature is represented as multiple rows in the * feature table. An example is UTR features in flybase - if a UTR spans multiple exons, each * part is a separate row in the feature table. In InterMine we represent the UTR as a single * object with a start and end so we need special handling for these types. * @return a list of segmented feature type */ protected List<String> getSegmentedFeatures() { return new ArrayList<String>(); } /** * Fix types from the feature table, perhaps by changing non-SO type into their SO equivalent. * Types that don't need fixing will be returned unchanged. * @param type the input type * @return the fixed type */ protected String fixFeatureType(String type) { if (type.equals("five_prime_untranslated_region")) { return "five_prime_UTR"; } else { if (type.equals("three_prime_untranslated_region")) { return "three_prime_UTR"; } else { return type; } } } /** * Do any extra processing that is needed before the converter starts querying features * @param connection the Connection * @throws ObjectStoreException if there is a object store problem * @throws SQLException if there is a database problem */ protected void earlyExtraProcessing(Connection connection) throws ObjectStoreException, SQLException { // override in subclasses as necessary } /** * Do any extra processing for this database, after all other processing is done * @param connection the Connection * @param featureDataMap a map from chado feature_id to data for that feature * @throws ObjectStoreException if there is a problem while storing * @throws SQLException if there is a problem */ protected void extraProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws ObjectStoreException, SQLException { // override in subclasses as necessary } /** * Perform any actions needed after all processing is finished. * @param connection the Connection * @param featureDataMap a map from chado feature_id to data for that feature * @throws ObjectStoreException if there is a problem while storing * @throws SQLException if there is a problem */ protected void finishedProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws ObjectStoreException, SQLException { // override in subclasses as necessary } /** * Process a featureloc table and create Location objects. * @param connection the Connectio * @param res a ResultSet that has the columns: featureloc_id, feature_id, srcfeature_id, * fmin, fmax, strand * @throws SQLException if there is a problem while querying * @throws ObjectStoreException if there is a problem while storing */ protected void processLocationTable(Connection connection, ResultSet res) throws SQLException, ObjectStoreException { int count = 0; int featureWarnings = 0; while (res.next()) { Integer featureLocId = new Integer(res.getInt("featureloc_id")); Integer featureId = new Integer(res.getInt("feature_id")); Integer srcFeatureId = new Integer(res.getInt("srcfeature_id")); int start = res.getInt("fmin") + 1; int end = res.getInt("fmax"); if (start < 1 || end < 1) { continue; } int strand = res.getInt("strand"); if (featureMap.containsKey(srcFeatureId)) { FeatureData srcFeatureData = featureMap.get(srcFeatureId); if (featureMap.containsKey(featureId)) { FeatureData featureData = featureMap.get(featureId); int taxonId = featureData.organismData.getTaxonId(); Item location = makeLocation(start, end, strand, srcFeatureData, featureData, taxonId); getChadoDBConverter().store(location); final String featureClassName = getModel().getPackageName() + "." + featureData.interMineType; Class<?> featureClass; try { featureClass = Class.forName(featureClassName); } catch (ClassNotFoundException e) { throw new RuntimeException("unable to find class object for setting " + "a chromosome reference", e); } if (LocatedSequenceFeature.class.isAssignableFrom(featureClass)) { Integer featureIntermineObjectId = featureData.getIntermineObjectId(); if (srcFeatureData.interMineType.equals("Chromosome")) { Reference chrReference = new Reference(); chrReference.setName("chromosome"); chrReference.setRefId(srcFeatureData.itemIdentifier); getChadoDBConverter().store(chrReference, featureIntermineObjectId); } Reference locReference = new Reference(); locReference.setName("chromosomeLocation"); locReference.setRefId(location.getIdentifier()); getChadoDBConverter().store(locReference, featureIntermineObjectId); if (!featureData.getFlag(FeatureData.LENGTH_SET)) { setAttribute(featureData.intermineObjectId, "length", String.valueOf(end - start + 1)); } } else { LOG.warn("featureId (" + featureId + ") from location " + featureLocId + " was expected to be a LocatedSequenceFeature"); } count++; } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("featureId (" + featureId + ") from location " + featureLocId + " was not found in the feature table"); } else { LOG.warn("further location warnings ignored"); } featureWarnings++; } } } else { throw new RuntimeException("srcfeature_id (" + srcFeatureId + ") from location " + featureLocId + " was not found in the feature table"); } } LOG.info("created " + count + " locations"); res.close(); } /** * Make a Location Relation between a LocatedSequenceFeature and a Chromosome. * @param start the start position * @param end the end position * @param strand the strand * @param srcFeatureData the FeatureData for the src feature (the Chromosome) * @param featureData the FeatureData for the LocatedSequenceFeature * @param taxonId the taxon id to use when finding the Chromosome for the Location * @return the new Location object * @throws ObjectStoreException if there is a problem while storing */ protected Item makeLocation(int start, int end, int strand, FeatureData srcFeatureData, FeatureData featureData, int taxonId) throws ObjectStoreException { Item location = getChadoDBConverter().makeLocation(srcFeatureData.itemIdentifier, featureData.itemIdentifier, start, end, strand, taxonId); return location; } /** * Use the feature_relationship table to set relations (references and collections) between * features. */ private void processRelationTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeatureRelationshipResultSet(connection); Integer lastSubjectId = null; // a Map from transcript object id to count of exons Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(); // Map from relation type to Map from object type to FeatureData - used to collect up all // the collection/reference information for one subject feature Map<String, Map<String, List<FeatureData>>> relTypeMap = new HashMap<String, Map<String, List<FeatureData>>>(); int featureWarnings = 0; int collectionWarnings = 0; int count = 0; int collectionTotal = 0; while (res.next()) { Integer featRelationshipId = new Integer(res.getInt("feature_relationship_id")); Integer subjectId = new Integer(res.getInt("subject_id")); Integer objectId = new Integer(res.getInt("object_id")); String relationTypeName = res.getString("type_name"); if (lastSubjectId != null && !subjectId.equals(lastSubjectId)) { if (!processCollectionData(lastSubjectId, relTypeMap, collectionWarnings)) { collectionWarnings++; if (collectionWarnings == 20) { LOG.warn("ignoring further unknown feature warnings from " + "processCollectionData()"); } } collectionTotal += relTypeMap.size(); relTypeMap = new HashMap<String, Map<String, List<FeatureData>>>(); } if (featureMap.containsKey(subjectId)) { if (featureMap.containsKey(objectId)) { FeatureData objectFeatureData = featureMap.get(objectId); Map<String, List<FeatureData>> objectClassFeatureDataMap; if (relTypeMap.containsKey(relationTypeName)) { objectClassFeatureDataMap = relTypeMap.get(relationTypeName); } else { objectClassFeatureDataMap = new HashMap<String, List<FeatureData>>(); relTypeMap.put(relationTypeName, objectClassFeatureDataMap); } List<FeatureData> featureDataList; if (objectClassFeatureDataMap.containsKey(objectFeatureData.interMineType)) { featureDataList = objectClassFeatureDataMap.get(objectFeatureData.interMineType); } else { featureDataList = new ArrayList<FeatureData>(); objectClassFeatureDataMap.put(objectFeatureData.interMineType, featureDataList); } featureDataList.add(objectFeatureData); // special case: collect data for setting Transcript.exonCount Class<?> objectClass; try { objectClass = Class.forName(getModel().getPackageName() + "." + objectFeatureData.interMineType); } catch (ClassNotFoundException e) { final String message = "can't find class for " + objectFeatureData.interMineType + "while processing relation: " + featRelationshipId; throw new RuntimeException(message); } if (Transcript.class.isAssignableFrom(objectClass)) { FeatureData subjectFeatureData = featureMap.get(subjectId); // XXX FIXME TODO Hacky special case: count the exons so we can set // exonCount later. Perhaps this should be configurable. if (subjectFeatureData.interMineType.equals("Exon")) { if (!countMap.containsKey(objectFeatureData.intermineObjectId)) { countMap.put(objectFeatureData.intermineObjectId, new Integer(1)); } else { Integer currentVal = countMap.get(objectFeatureData.intermineObjectId); countMap.put(objectFeatureData.intermineObjectId, new Integer(currentVal.intValue() + 1)); } } } } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("object_id " + objectId + " from feature_relationship " + featRelationshipId + " was not found in the feature table"); } else { LOG.warn("further feature_relationship warnings ignored"); } featureWarnings++; } } } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("subject_id " + subjectId + " from feature_relationship " + featRelationshipId + " was not found in the feature table"); } else { LOG.warn("further feature_relationship warnings ignored"); } featureWarnings++; } } count++; lastSubjectId = subjectId; } if (lastSubjectId != null) { processCollectionData(lastSubjectId, relTypeMap, collectionWarnings); // Stores stuff collectionTotal += relTypeMap.size(); } LOG.info("processed " + count + " relations"); LOG.info("total collection elements created: " + collectionTotal); res.close(); // XXX FIXME TODO Hacky special case: set the exonCount fields for (Map.Entry<Integer, Integer> entry: countMap.entrySet()) { Integer featureId = entry.getKey(); Integer collectionCount = entry.getValue(); setAttribute(featureId, "exonCount", String.valueOf(collectionCount)); } } /** * Create collections and references for the Item given by chadoSubjectId. * @param collectionWarnings */ private boolean processCollectionData(Integer chadoSubjectId, Map<String, Map<String, List<FeatureData>>> relTypeMap, int collectionWarnings) throws ObjectStoreException { FeatureData subjectData = featureMap.get(chadoSubjectId); if (subjectData == null) { if (collectionWarnings < 20) { LOG.warn("unknown feature " + chadoSubjectId + " passed to processCollectionData - " + "ignoring"); } return false; } // map from collection name to list of item ids Map<String, List<String>> collectionsToStore = new HashMap<String, List<String>>(); String subjectInterMineType = subjectData.interMineType; ClassDescriptor cd = getModel().getClassDescriptorByName(subjectInterMineType); Integer intermineObjectId = subjectData.intermineObjectId; for (Map.Entry<String, Map<String, List<FeatureData>>> entry: relTypeMap.entrySet()) { String relationType = entry.getKey(); Map<String, List<FeatureData>> objectClassFeatureDataMap = entry.getValue(); Set<Entry<String, List<FeatureData>>> mapEntries = objectClassFeatureDataMap.entrySet(); for (Map.Entry<String, List<FeatureData>> featureDataMap: mapEntries) { String objectClass = featureDataMap.getKey(); List<FeatureData> featureDataCollection = featureDataMap.getValue(); List<FieldDescriptor> fds = null; FeatureData subjectFeatureData = featureMap.get(chadoSubjectId); // key example: ("relationship", "Translation", "producedby", "MRNA") MultiKey key = new MultiKey("relationship", subjectFeatureData.interMineType, relationType, objectClass); List<ConfigAction> actionList = getConfig(subjectData.organismData.getTaxonId()).get(key); if (actionList != null) { if (actionList.size() == 0 || actionList.size() == 1 && actionList.get(0) instanceof DoNothingAction) { // do nothing continue; } fds = new ArrayList<FieldDescriptor>(); for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; String fieldName = setAction.getFieldName(); FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName); if (fd == null) { throw new RuntimeException("can't find field " + fieldName + " in class " + cd + " configured for " + key); } else { fds.add(fd); } } } if (fds.size() == 0) { throw new RuntimeException("no actions found for " + key); } } else { if (PARTOF_RELATIONS.contains(relationType)) { // special case for part_of relations - try to find a reference or // collection that has a name that looks right for these objects (of class // objectClass). eg. If the subject is a Transcript and the objectClass // is Exon then find collections called "exons", "geneParts" (GenePart is // a superclass of Exon) fds = getReferenceForRelationship(objectClass, cd); } else { continue; } } if (fds.size() == 0) { LOG.error("can't find collection for type " + relationType + " in " + subjectInterMineType + " while processing feature " + chadoSubjectId); continue; } for (FieldDescriptor fd: fds) { if (fd.isReference()) { if (objectClassFeatureDataMap.size() > 1) { throw new RuntimeException("found more than one object for reference " + fd + " in class " + subjectInterMineType + " current subject identifier: " + subjectData.uniqueName); } else { if (objectClassFeatureDataMap.size() == 1) { Reference reference = new Reference(); reference.setName(fd.getName()); FeatureData referencedFeatureData = featureDataCollection.get(0); reference.setRefId(referencedFeatureData.itemIdentifier); getChadoDBConverter().store(reference, intermineObjectId); // special case for 1-1 relations - we need to set the reverse // reference ReferenceDescriptor rd = (ReferenceDescriptor) fd; ReferenceDescriptor reverseRD = rd.getReverseReferenceDescriptor(); if (reverseRD != null && !reverseRD.isCollection()) { Reference revReference = new Reference(); revReference.setName(reverseRD.getName()); revReference.setRefId(subjectData.itemIdentifier); Integer refObjectId = referencedFeatureData.intermineObjectId; getChadoDBConverter().store(revReference, refObjectId); } } } } else { List<String> itemIds; if (collectionsToStore.containsKey(fd.getName())) { itemIds = collectionsToStore.get(fd.getName()); } else { itemIds = new ArrayList<String>(); collectionsToStore.put(fd.getName(), itemIds); } for (FeatureData featureData: featureDataCollection) { itemIds.add(featureData.itemIdentifier); } } } } } for (Map.Entry<String, List<String>> entry: collectionsToStore.entrySet()) { ReferenceList referenceList = new ReferenceList(); String collectionName = entry.getKey(); referenceList.setName(collectionName); List<String> idList = entry.getValue(); referenceList.setRefIds(idList); getChadoDBConverter().store(referenceList, intermineObjectId); // if there is a field called <classname>Count that matches the name of the collection // we just stored, set it String countName; if (collectionName.endsWith("s")) { countName = collectionName.substring(0, collectionName.length() - 1); } else { countName = collectionName; } countName += "Count"; if (cd.getAttributeDescriptorByName(countName, true) != null) { setAttribute(intermineObjectId, countName, String.valueOf(idList.size())); } } return true; } /** * Search ClassDescriptor cd class for refs/collections with the right name for the objectType * eg. find CDSs collection for objectType = CDS and find gene reference for objectType = Gene. */ private List<FieldDescriptor> getReferenceForRelationship(String objectType, ClassDescriptor cd) { List<FieldDescriptor> fds = new ArrayList<FieldDescriptor>(); LinkedHashSet<String> allClasses = new LinkedHashSet<String>(); allClasses.add(objectType); try { Set<String> parentClasses = ClassDescriptor.findSuperClassNames(getModel(), objectType); allClasses.addAll(parentClasses); } catch (MetaDataException e) { throw new RuntimeException("class not found in the model", e); } for (String clsName: allClasses) { List<String> possibleRefNames = new ArrayList<String>(); String unqualifiedClsName = TypeUtil.unqualifiedName(clsName); possibleRefNames.add(unqualifiedClsName); possibleRefNames.add(unqualifiedClsName + 's'); possibleRefNames.add(StringUtil.decapitalise(unqualifiedClsName)); possibleRefNames.add(StringUtil.decapitalise(unqualifiedClsName) + 's'); for (String possibleRefName: possibleRefNames) { FieldDescriptor fd = cd.getFieldDescriptorByName(possibleRefName); if (fd != null) { fds.add(fd); } } } return fds; } private void processDbxrefTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getDbxrefResultSet(connection); Set<String> existingAttributes = new HashSet<String>(); Integer currentFeatureId = null; int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String accession = res.getString("accession"); String dbName = res.getString("db_name"); Boolean isCurrent = res.getBoolean("is_current"); if (currentFeatureId != null && currentFeatureId != featureId) { existingAttributes = new HashSet<String>(); } if (featureMap.containsKey(featureId)) { FeatureData fdat = featureMap.get(featureId); accession = fixIdentifier(fdat.interMineType, accession); MultiKey key = new MultiKey("dbxref", fdat.interMineType, dbName, isCurrent); int taxonId = fdat.organismData.getTaxonId(); Map<MultiKey, List<ConfigAction>> orgConfig = getConfig(taxonId); List<ConfigAction> actionList = orgConfig.get(key); if (actionList == null) { // try ignoring isCurrent MultiKey key2 = new MultiKey("dbxref", fdat.interMineType, dbName, null); actionList = orgConfig.get(key2); } if (actionList == null) { // no actions configured for this synonym continue; } Set<String> fieldsSet = new HashSet<String>(); for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (!existingAttributes.contains(setAction.getFieldName())) { if (setAction.isValidValue(accession)) { String newFieldValue = setAction.processValue(accession); setAttribute(fdat.intermineObjectId, setAction.getFieldName(), newFieldValue); existingAttributes.add(setAction.getFieldName()); fieldsSet.add(newFieldValue); if (setAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } } } for (ConfigAction action: actionList) { if (action instanceof CreateSynonymAction) { CreateSynonymAction createSynonymAction = (CreateSynonymAction) action; if (!createSynonymAction.isValidValue(accession)) { continue; } String newFieldValue = createSynonymAction.processValue(accession); if (fdat.existingSynonyms.contains(newFieldValue)) { continue; } else { boolean isPrimary = false; if (fieldsSet.contains(newFieldValue)) { isPrimary = true; } Item synonym = createSynonym(fdat, "identifier", newFieldValue, isPrimary, null); getChadoDBConverter().store(synonym); count++; } } } } currentFeatureId = featureId; } LOG.info("created " + count + " synonyms from the dbxref table"); res.close(); } private void processFeaturePropTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeaturePropResultSet(connection); int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String identifier = res.getString("value"); if (identifier == null) { continue; } String propTypeName = res.getString("type_name"); if (featureMap.containsKey(featureId)) { FeatureData fdat = featureMap.get(featureId); MultiKey key = new MultiKey("prop", fdat.interMineType, propTypeName); int taxonId = fdat.organismData.getTaxonId(); List<ConfigAction> actionList = getConfig(taxonId).get(key); if (actionList == null) { // no actions configured for this prop continue; } Set<String> fieldsSet = new HashSet<String>(); for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (setAction.isValidValue(identifier)) { String newFieldValue = setAction.processValue(identifier); setAttribute(fdat.intermineObjectId, setAction.getFieldName(), newFieldValue); fieldsSet.add(newFieldValue); if (setAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } } for (ConfigAction action: actionList) { if (action instanceof CreateSynonymAction) { CreateSynonymAction synonymAction = (CreateSynonymAction) action; if (!synonymAction.isValidValue(identifier)) { continue; } String newFieldValue = synonymAction.processValue(identifier); Set<String> existingSynonyms = fdat.existingSynonyms; if (existingSynonyms.contains(newFieldValue)) { continue; } else { String synonymType = synonymAction.getSynonymType(); if (synonymType == null) { synonymType = propTypeName; } boolean isPrimary = false; if (fieldsSet.contains(newFieldValue)) { isPrimary = true; } Item synonym = createSynonym(fdat, synonymType, newFieldValue, isPrimary, null); getChadoDBConverter().store(synonym); count++; } } } } } LOG.info("created " + count + " synonyms from the featureprop table"); res.close(); } /** * Read the feature, feature_cvterm and cvterm tables, then set fields, create synonyms or * create objects based on the cvterms. * @param connection the Connection */ private void processFeatureCVTermTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeatureCVTermResultSet(connection); int count = 0; Integer previousFeatureId = null; // map from reference/collection name to list of Items to store in the reference or // collection Map<String, List<Item>> dataMap = new HashMap<String, List<Item>>(); while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String cvtermName = res.getString("cvterm_name"); String cvName = res.getString("cv_name"); FeatureData fdat = featureMap.get(featureId); if (fdat == null) { continue; } if (!featureId.equals(previousFeatureId) && previousFeatureId != null) { processCVTermRefCols(previousFeatureId, dataMap); dataMap = new HashMap<String, List<Item>>(); } MultiKey key = new MultiKey("cvterm", fdat.interMineType, cvName); int taxonId = fdat.organismData.getTaxonId(); List<ConfigAction> actionList = getConfig(taxonId).get(key); if (actionList == null) { // no actions configured for this prop continue; } Set<String> fieldsSet = new HashSet<String>(); for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (setAction.isValidValue(cvtermName)) { String newFieldValue = setAction.processValue(cvtermName); setAttribute(fdat.intermineObjectId, setAction.getFieldName(), newFieldValue); fieldsSet.add(newFieldValue); if (setAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } else { if (action instanceof CreateSynonymAction) { CreateSynonymAction synonymAction = (CreateSynonymAction) action; if (!synonymAction.isValidValue(cvtermName)) { continue; } String newFieldValue = synonymAction.processValue(cvtermName); Set<String> existingSynonyms = fdat.existingSynonyms; if (existingSynonyms.contains(newFieldValue)) { continue; } else { String synonymType = synonymAction.getSynonymType(); boolean isPrimary = false; if (fieldsSet.contains(newFieldValue)) { isPrimary = true; } Item synonym = createSynonym(fdat, synonymType, newFieldValue, isPrimary, null); getChadoDBConverter().store(synonym); count++; } } else { if (action instanceof CreateCollectionAction) { CreateCollectionAction cca = (CreateCollectionAction) action; Item item = null; String fieldName = cca.getFieldName(); String className = cca.getClassName(); if (cca.createSingletons()) { MultiKey singletonKey = new MultiKey(className, fieldName, cvtermName); item = (Item) singletonMap.get(singletonKey); } if (item == null) { item = getChadoDBConverter().createItem(className); item.setAttribute(fieldName, cvtermName); getChadoDBConverter().store(item); if (cca.createSingletons()) { singletonMap.put(key, item); } } String referenceName = cca.getReferenceName(); List<Item> itemList; if (dataMap.containsKey(referenceName)) { itemList = dataMap.get(referenceName); } else { itemList = new ArrayList<Item>(); dataMap.put(referenceName, itemList); } itemList.add(item); } } } } previousFeatureId = featureId; } if (previousFeatureId != null) { processCVTermRefCols(previousFeatureId, dataMap); } LOG.info("created " + count + " synonyms from the feature_cvterm table"); res.close(); } /** * Given the object id and a map of reference/collection names to Items, store the Items in the * reference or collection of the object. */ private void processCVTermRefCols(Integer chadoObjectId, Map<String, List<Item>> dataMap) throws ObjectStoreException { FeatureData fdat = featureMap.get(chadoObjectId); String interMineType = fdat.interMineType; ClassDescriptor cd = getModel().getClassDescriptorByName(interMineType); for (String referenceName: dataMap.keySet()) { FieldDescriptor fd = cd.getFieldDescriptorByName(referenceName); if (fd == null) { throw new RuntimeException("failed to find " + referenceName + " in " + interMineType); } List<Item> itemList = dataMap.get(referenceName); Integer intermineObjectId = fdat.getIntermineObjectId(); if (fd.isReference()) { if (itemList.size() > 1) { throw new RuntimeException("found more than one object for reference " + fd + " in class " + interMineType + " items: " + itemList); } else { Item item = itemList.iterator().next(); Reference reference = new Reference(); reference.setName(fd.getName()); String itemIdentifier = item.getIdentifier(); reference.setRefId(itemIdentifier); getChadoDBConverter().store(reference, intermineObjectId); // XXX FIXME TODO: special case for 1-1 relations - we need to set the reverse // reference } } else { ReferenceList referenceList = new ReferenceList(); referenceList.setName(referenceName); for (Item item: itemList) { referenceList.addRefId(item.getIdentifier()); } getChadoDBConverter().store(referenceList, intermineObjectId); } } } private void processSynonymTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getSynonymResultSet(connection); Set<String> existingAttributes = new HashSet<String>(); Integer currentFeatureId = null; int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String identifier = res.getString("synonym_name"); String synonymTypeName = res.getString("type_name"); Boolean isCurrent = res.getBoolean("is_current"); identifier = fixIdentifier(synonymTypeName, identifier); if (currentFeatureId != null && currentFeatureId != featureId) { existingAttributes = new HashSet<String>(); } if (featureMap.containsKey(featureId)) { FeatureData fdat = featureMap.get(featureId); MultiKey key = new MultiKey("synonym", fdat.interMineType, synonymTypeName, isCurrent); int taxonId = fdat.organismData.getTaxonId(); Map<MultiKey, List<ConfigAction>> orgConfig = getConfig(taxonId); List<ConfigAction> actionList = orgConfig.get(key); if (actionList == null) { // try ignoring isCurrent MultiKey key2 = new MultiKey("synonym", fdat.interMineType, synonymTypeName, null); actionList = orgConfig.get(key2); } if (actionList == null) { // no actions configured for this synonym continue; } boolean setField = false; for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (!existingAttributes.contains(setAction.getFieldName()) && setAction.isValidValue(identifier)) { String newFieldValue = setAction.processValue(identifier); setAttribute(fdat.intermineObjectId, setAction.getFieldName(), newFieldValue); existingAttributes.add(setAction.getFieldName()); setField = true; if (setAction.getFieldName().equals("primaryIdentifier")) { fdat.setFlag(FeatureData.IDENTIFIER_SET, true); } } } } for (ConfigAction action: actionList) { if (action instanceof CreateSynonymAction) { CreateSynonymAction createSynonymAction = (CreateSynonymAction) action; if (!createSynonymAction.isValidValue(identifier)) { continue; } String newFieldValue = createSynonymAction.processValue(identifier); if (fdat.existingSynonyms.contains(newFieldValue)) { continue; } else { Item synonym = createSynonym(fdat, synonymTypeName, newFieldValue, setField, null); getChadoDBConverter().store(synonym); count++; } } } } currentFeatureId = featureId; } LOG.info("created " + count + " synonyms from the synonym table"); res.close(); } /** * Process the identifier and return a "cleaned" version. Implement in sub-classes to fix * data problem. * @param type the InterMine type of the feature that this identifier came from * @param identifier the identifier * @return a cleaned identifier */ protected String fixIdentifier(String type, String identifier) { return identifier; } private void processPubTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getPubResultSet(connection); List<String> currentPublicationIds = new ArrayList<String>(); Integer lastPubFeatureId = null; int featureWarnings = 0; int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); if (!featureMap.containsKey(featureId)) { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("feature " + featureId + " not found in features Map while " + "processing publications"); } else { LOG.warn("further feature id warnings ignored in processPubTable()"); } featureWarnings++; } continue; } Integer pubMedId = Integer.parseInt(res.getString("pub_db_identifier")); if (lastPubFeatureId != null && !featureId.equals(lastPubFeatureId)) { makeFeaturePublications(lastPubFeatureId, currentPublicationIds); currentPublicationIds = new ArrayList<String>(); } String publicationId = makePublication(pubMedId); currentPublicationIds.add(publicationId); lastPubFeatureId = featureId; count++; } if (lastPubFeatureId != null) { makeFeaturePublications(lastPubFeatureId, currentPublicationIds); } LOG.info("Created " + count + " publications"); res.close(); } /** * Return the item identifier of the publication Item for the given pubmed id. * @param pubMedId the pubmed id * @return the publication item id * @throws ObjectStoreException if the item can't be stored */ protected String makePublication(Integer pubMedId) throws ObjectStoreException { if (publications.containsKey(pubMedId)) { return publications.get(pubMedId); } else { Item publication = getChadoDBConverter().createItem("Publication"); publication.setAttribute("pubMedId", pubMedId.toString()); getChadoDBConverter().store(publication); // Stores Publication String publicationId = publication.getIdentifier(); publications.put(pubMedId, publicationId); return publicationId; } } /** * Set the publications collection of the feature with the given (chado) feature id. */ private void makeFeaturePublications(Integer featureId, List<String> argPublicationIds) throws ObjectStoreException { FeatureData fdat = featureMap.get(featureId); if (fdat == null) { throw new RuntimeException("feature " + featureId + " not found in features Map"); } if (argPublicationIds.size() == 0) { return; } List<String> publicationIds = new ArrayList<String>(argPublicationIds); ReferenceList referenceList = new ReferenceList(); referenceList.setName("publications"); referenceList.setRefIds(publicationIds); getChadoDBConverter().store(referenceList, fdat.intermineObjectId); } /** * Return the interesting rows from the features table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureResultSet(Connection connection) throws SQLException { String query = "SELECT * FROM " + tempFeatureTableName; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Convert the list of features to a string to be used in a SQL query. * @return the list of features as a string (in SQL list format) */ private String getFeaturesString(List<String> featuresList) { StringBuffer featureListString = new StringBuffer(); Iterator<String> i = featuresList.iterator(); while (i.hasNext()) { String item = i.next(); featureListString.append("'" + item + "'"); if (i.hasNext()) { featureListString.append(", "); } } return featureListString.toString(); } /** * Return a comma separated string containing the organism_ids that with with to query from * chado. */ private String getOrganismIdsString() { return StringUtil.join(getChadoDBConverter().getChadoIdToOrgDataMap().keySet(), ", "); } /** * Create a temporary table containing only the features that interest us. Also create indexes * for the type and feature_id columns. * The table is used in later queries. This is a protected method so that it can be overriden * for testing. * @param connection the Connection * @throws SQLException if there is a problem */ protected void createFeatureTempTable(Connection connection) throws SQLException { List<String> featuresList = new ArrayList<String>(getFeatures()); featuresList.addAll(getChromosomeFeatureTypes()); String featureTypesString = getFeaturesString(featuresList); String organismConstraint = getOrganismConstraint(); String orgConstraintForQuery = ""; if (!StringUtils.isEmpty(organismConstraint)) { orgConstraintForQuery = " AND " + organismConstraint; } String query = "CREATE TEMPORARY TABLE " + tempFeatureTableName + " AS" + " SELECT feature_id, feature.name, uniquename, cvterm.name as type, seqlen," + " is_analysis, residues, organism_id" + " FROM feature, cvterm" + " WHERE cvterm.name IN (" + featureTypesString + ")" + orgConstraintForQuery + " AND NOT feature.is_obsolete" + " AND feature.type_id = cvterm.cvterm_id " + (getExtraFeatureConstraint() != null ? " AND (" + getExtraFeatureConstraint() + ")" : ""); Statement stmt = connection.createStatement(); LOG.info("executing: " + query); stmt.execute(query); String idIndexQuery = "CREATE INDEX " + tempFeatureTableName + "_feature_index ON " + tempFeatureTableName + "(feature_id)"; LOG.info("executing: " + idIndexQuery); stmt.execute(idIndexQuery); String typeIndexQuery = "CREATE INDEX " + tempFeatureTableName + "_type_index ON " + tempFeatureTableName + "(type)"; LOG.info("executing: " + typeIndexQuery); stmt.execute(typeIndexQuery); String analyze = "ANALYZE " + tempFeatureTableName; LOG.info("executing: " + analyze); stmt.execute(analyze); } /** * Return some SQL that can be included in the WHERE part of query that restricts features * by organism. "organism_id" must be selected. * @return the SQL */ protected String getOrganismConstraint() { String organismIdsString = getOrganismIdsString(); if (StringUtils.isEmpty(organismIdsString)) { return ""; } else { return "organism_id IN (" + organismIdsString + ")"; } } /** * Return an extra constraint to be used when querying the feature table. Any feature table * column or cvterm table column can be constrained. The cvterm will match the type_id field * in the feature. * eg. "uniquename not like 'BAD_ID%'" * @return the constraint as SQL or nul if there is no extra constraint. */ protected String getExtraFeatureConstraint() { // no default return null; } /** * Return an SQL query that finds the feature_ids of all rows from the feature table that we * need to process. * @return the SQL string */ protected String getFeatureIdQuery() { return "SELECT feature_id FROM " + tempFeatureTableName; } private String getChromosomeFeatureIdQuery() { return "SELECT feature_id FROM feature, cvterm" + " WHERE type_id = cvterm.cvterm_id" + " AND cvterm.name IN (" + getFeaturesString(getChromosomeFeatureTypes()) + ")" + (getExtraFeatureConstraint() != null ? " AND (" + getExtraFeatureConstraint() + ")" : ""); } /** * Return the interesting rows from the feature_relationship table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureRelationshipResultSet(Connection connection) throws SQLException { String query = "SELECT feature_relationship_id, subject_id, object_id, cvterm.name AS type_name" + " FROM feature_relationship, cvterm" + " WHERE cvterm.cvterm_id = type_id" + " AND subject_id IN (" + getFeatureIdQuery() + ")" + " AND object_id IN (" + getFeatureIdQuery() + ")" + " ORDER BY subject_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the featureloc table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureLocResultSet(Connection connection) throws SQLException { String query = "SELECT featureloc_id, feature_id, srcfeature_id, fmin, is_fmin_partial," + " fmax, is_fmax_partial, strand" + " FROM featureloc" + " WHERE feature_id IN" + " (" + getFeatureIdQuery() + ")" + " AND srcfeature_id IN" + " (" + getChromosomeFeatureIdQuery() + ")" + " AND locgroup = 0"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting matches from the featureloc and feature tables. * feature<->featureloc<->match_feature<->featureloc<->feature * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getMatchLocResultSet(Connection connection) throws SQLException { String query = "SELECT f1loc.featureloc_id, f1.feature_id, f2.feature_id AS srcfeature_id, f2loc.fmin," + " false AS is_fmin_partial, f2loc.fmax, false AS is_fmax_partial, f2loc.strand" + " FROM feature match, feature f1, featureloc f1loc, feature f2, featureloc f2loc," + " cvterm mt" + " WHERE match.feature_id = f1loc.feature_id AND match.feature_id = f2loc.feature_id" + " AND f1loc.srcfeature_id = f1.feature_id AND f2loc.srcfeature_id = f2.feature_id" + " AND match.type_id = mt.cvterm_id AND mt.name IN ('match', 'cDNA_match')" + " AND f1.feature_id <> f2.feature_id" + " AND f1.feature_id IN (" + getFeatureIdQuery() + ")" + " AND f2.feature_id IN (" + getChromosomeFeatureIdQuery() + ")"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the dbxref table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDbxrefResultSet(Connection connection) throws SQLException { String query = "SELECT feature.feature_id, accession, db.name AS db_name, is_current" + " FROM dbxref, feature_dbxref, feature, db" + " WHERE feature_dbxref.dbxref_id = dbxref.dbxref_id " + " AND feature_dbxref.feature_id = feature.feature_id " + " AND feature.feature_id IN" + " (" + getFeatureIdQuery() + ")" + " AND dbxref.db_id = db.db_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the featureprop table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeaturePropResultSet(Connection connection) throws SQLException { String query = "select feature_id, value, cvterm.name AS type_name FROM featureprop, cvterm" + " WHERE featureprop.type_id = cvterm.cvterm_id" + " AND feature_id IN (" + getFeatureIdQuery() + ")"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the feature_cvterm/cvterm table. Only returns rows for * those features returned by getFeatureIdQuery(). * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureCVTermResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature_id, cvterm.cvterm_id, cvterm.name AS cvterm_name," + " cv.name AS cv_name " + " FROM feature_cvterm, cvterm, cv " + " WHERE feature_id IN (" + getFeatureIdQuery() + ")" + " AND cvterm.cvterm_id = feature_cvterm.cvterm_id " + " AND cvterm.cv_id = cv.cv_id " + " ORDER BY feature_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the synonym table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSynonymResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature_id, synonym.name AS synonym_name," + " cvterm.name AS type_name, is_current" + " FROM feature_synonym, synonym, cvterm" + " WHERE feature_synonym.synonym_id = synonym.synonym_id" + " AND synonym.type_id = cvterm.cvterm_id" + " AND feature_id IN (" + getFeatureIdQuery() + ")" + " ORDER BY is_current DESC"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the pub table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getPubResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature_pub.feature_id, dbxref.accession as pub_db_identifier" + " FROM feature_pub, dbxref, db, pub, pub_dbxref" + " WHERE feature_pub.pub_id = pub.pub_id" + " AND pub_dbxref.dbxref_id = dbxref.dbxref_id" + " AND dbxref.db_id = db.db_id" + " AND pub.pub_id = pub_dbxref.pub_id" + " AND db.name = 'pubmed'" + " AND feature_id IN (" + getFeatureIdQuery() + ")" + " ORDER BY feature_pub.feature_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Call DataConverter.createSynonym(), store the Item then record in FeatureData that we've * created it. * @param fdat the FeatureData * @param type the synonym type * @param identifier the identifier to store in the Synonym * @param isPrimary true if the synonym is a primary identifier * @param otherEvidence the evidence collection to store in the Synonym * @return the new Synonym * @throws ObjectStoreException if there is a problem while storing */ protected Item createSynonym(FeatureData fdat, String type, String identifier, boolean isPrimary, List<Item> otherEvidence) throws ObjectStoreException { if (fdat.existingSynonyms.contains(identifier)) { throw new IllegalArgumentException("feature identifier " + identifier + " is already a synonym for: " + fdat.existingSynonyms); } List<Item> allEvidence = new ArrayList<Item>(); if (otherEvidence != null) { allEvidence.addAll(otherEvidence); } Item returnItem = getChadoDBConverter().createSynonym(fdat.itemIdentifier, type, identifier, isPrimary, allEvidence); fdat.existingSynonyms.add(identifier); return returnItem; } /** * Fetch the populated map of chado feature id to FeatureData objects. * @return map of feature details */ protected Map<Integer, FeatureData> getFeatureMap() { return this.featureMap; } /** * Fetch the populated map of chromosome-like features. The keys are the chromosome uniqueName * fields and the values are the chado feature_ids. * @param organismId the chado organism_id * @return map of chromosome details */ protected Map<String, Integer> getChromosomeFeatureMap(Integer organismId) { return chromosomeMaps.get(organismId); } /** * Data about one feature from the feature table in chado. This exists to avoid having lots of * Item objects in memory. * * @author Kim Rutherford */ protected static class FeatureData { private OrganismData organismData; private String uniqueName; private String chadoFeatureName; // the synonyms that have already been created private final Set<String> existingSynonyms = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); private String itemIdentifier; private String interMineType; private Integer intermineObjectId; private short flagss = 0; static final short EVIDENCE_CREATED = 0; static final short IDENTIFIER_SET = 1; static final short LENGTH_SET = 2; static final short DATASET_SET = 3; /** * Return the id of the Item representing this feature. * @return the ID */ public Integer getIntermineObjectId() { return intermineObjectId; } /** * Get the String read from the name column of the feature table. * @return the name */ public String getChadoFeatureName() { return chadoFeatureName; } /** * Get the String read from the uniquename column of the feature table. * @return the uniquename */ public String getChadoFeatureUniqueName() { return uniqueName; } /** * Return the InterMine Item identifier for this feature. * @return the InterMine Item identifier */ public String getItemIdentifier() { return itemIdentifier; } /** * Return the OrganismData object for the organism this feature comes from. * @return the OrganismData object */ public OrganismData getOrganismData() { return organismData; } /** * Return the InterMine type of this object * @return the InterMine type */ public String getInterMineType() { return interMineType; } private int shift(short flag) { return (2 << flag); } /** * Get the given flag. * @param flag the flag constant eg. LENGTH_SET_BIT * @return true if the flag is set */ public boolean getFlag(short flag) { return (flagss & shift(flag)) != 0; } /** * Set a flag * @param flag the flag constant * @param value the new value */ public void setFlag(short flag, boolean value) { if (value) { flagss |= shift(flag); } else { flagss &= ~shift(flag); } } } }
package org.intermine.bio.dataconversion; import java.util.*; import org.intermine.InterMineException; import org.intermine.xml.full.Item; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.ItemHelper; import org.intermine.objectstore.ObjectStoreException; import org.intermine.dataconversion.*; import org.intermine.metadata.Model; import org.intermine.util.XmlUtil; import org.apache.log4j.Logger; /** * Translates the interpro src items database into the interpro tgt items database * prior to dataloading. * * @author Peter Mclaren */ public class InterproDataTranslator extends DataTranslator { protected static final String PARENTFEATURES = "parentFeatures"; protected static final String CHILDFEATURES = "childFeatures"; protected static final String CONTAINS = "contains"; protected static final String FOUNDIN = "foundIn"; protected static final String PROTEINS = "proteins"; protected static final String PROTEINFEATURES = "proteinFeatures"; protected static final String CV_DATABASE = "cv_database"; protected static final String CV_ENTRY_TYPE = "cv_entry_type"; protected static final String CV_RELATION = "cv_relation"; protected static final String CV_EVIDENCE = "cv_evidence"; protected static final String ABBREV = "abbrev"; protected static final String IDENTIFIER = "identifier"; protected static final String COMMENTS = "comments"; protected static final String PROTEIN = "protein"; protected static final String METHOD = "method"; protected static final String ENTRY = "entry"; protected static final String MATCHES = "matches"; protected static final String ENTRY2ENTRY = "entry2entry"; protected static final String ENTRY2COMP = "entry2comp"; protected static final String COMMON_ANNOTATION = "common_annotation"; protected static final String FAMILY = "Family"; protected static final String DOMAIN = "Domain"; protected static final String PARENT = "parent"; protected static final String ENTRY1 = "entry1"; protected static final String ENTRY2 = "entry2"; protected static final String RELATIONSHIP = "relationship"; protected static final String PROTEIN_AC = "protein_ac"; protected static final String NAME = "name"; protected static final String ENTRY_AC = "entry_ac"; protected static final String METHOD_AC = "method_ac"; protected static final String EVIDENCE = "evidence"; protected static final String SOURCE = "source"; protected static final String SYNONYMS = "synonyms"; protected static final String PRIMARYACCESSION = "primaryAccession"; protected static final Logger LOG = Logger.getLogger(InterproDataTranslator.class); //little evidence tag item... private org.intermine.xml.full.Item interproDataSet = null; // private HashMap dbNameToDbSourceItemMap; // private HashMap dataSourceToDbSetItemMap; private Item interproDataSource = null; private org.intermine.xml.full.Reference interproDataSourceReference = null; private String org180454Identifier; /** * Typical constructor * * @param itemReader - the item reader * @param properties - some properties * @param sourceModel - the source model * @param targetModel - the target model */ public InterproDataTranslator(ItemReader itemReader, Properties properties, Model sourceModel, Model targetModel) { super(itemReader, properties, sourceModel, targetModel); interproDataSource = createItem("DataSource"); interproDataSource.addAttribute(new Attribute("name", "UniProtKB")); interproDataSourceReference = new org.intermine.xml.full.Reference(SOURCE, interproDataSource.getIdentifier()); interproDataSet = createItem("DataSet"); interproDataSet.setAttribute("title", "UniProtKB data set"); interproDataSet.setReference("dataSource", interproDataSource); // dbNameToDbSourceItemMap = new HashMap(); // dbNameToDbSourceItemMap.put("InterPro", // new DataSourceAndSetUsageCounter(interproDataSource, interproDataSet)); // dataSourceToDbSetItemMap = new HashMap(); // dataSourceToDbSetItemMap.put(interproDataSource, interproDataSet); } /** * {@inheritDoc} */ public void translate(ItemWriter tgtItemWriter) throws ObjectStoreException, InterMineException { org180454Identifier = itemFactory.makeItem().getIdentifier(); tgtItemWriter.store(ItemHelper.convert(interproDataSet)); tgtItemWriter.store(ItemHelper.convert(interproDataSource)); super.translate(tgtItemWriter); } /** * @see DataTranslator#translateItem() * {@inheritDoc} */ @Override protected Collection<Item> translateItem(Item srcItem) throws ObjectStoreException, InterMineException { // Needed so that STAX can find it's implementation classes ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Collection<Item> result = new HashSet(); String srcItemClassName = XmlUtil.getFragmentFromURI(srcItem.getClassName()); if (srcItemClassName.equalsIgnoreCase("cv_database") && "InterPro".equalsIgnoreCase(srcItem.getAttribute("dbname").getValue())) { //skip this one, since we deal with it manually... LOG.debug("SKIPPING STORE FOR THE CV_DATABASE.InterPro ITEM!"); } else { Collection<Item> translated = super.translateItem(srcItem); if (srcItemClassName.equals("taxonomy")) { result = translated; if (translated.size() != 1) { throw new RuntimeException("didn't get one target item when translating an " + "organism"); } else { Item organism = translated.iterator().next(); if (organism.getAttribute("taxonId").getValue().equals("7165")) { result = Collections.EMPTY_SET; } if (organism.getAttribute("taxonId").getValue().equals("180454")) { organism.setIdentifier(org180454Identifier); } } } else { if (translated != null) { for (Iterator i = translated.iterator(); i.hasNext();) { Item tgtItem = (Item) i.next(); if (PROTEIN.equals(srcItemClassName)) { result.addAll(processProteinItem(srcItem, tgtItem)); } else if (METHOD.equals(srcItemClassName)) { result.addAll(processMethodItem(srcItem, tgtItem)); } else if (ENTRY.equals(srcItemClassName)) { result.addAll(processEntryItem(srcItem, tgtItem)); } else if (MATCHES.equals(srcItemClassName)) { processMatchesItem(srcItem, tgtItem); } else if (COMMON_ANNOTATION.equals(srcItemClassName)) { processCommonAnnotationItem(tgtItem); } if (tgtItem != null) { result.add(tgtItem); } } } else { if (CV_DATABASE.equals(srcItemClassName)) { //processCVDatabaseItem(srcItem); } else { LOG.debug("SKIPPING AN UNTRANSLATED CLASS:" + srcItemClassName); } } } } return result; } catch (Exception e2) { throw new RuntimeException(e2); } finally { Thread.currentThread().setContextClassLoader(cl); } } private Set processProteinItem( org.intermine.xml.full.Item srcItem, org.intermine.xml.full.Item tgtItem) throws ObjectStoreException { org.intermine.xml.full.Item taxItem = getItemViaItemPath(srcItem, TAXONOMY_FROM_PROTEIN, srcItemReader); if (taxItem != null) { String taxonId = taxItem.getAttribute("taxa_id").getValue(); if ("180454".equals(taxonId) || "7165".equals(taxonId)) { tgtItem.setReference("organism", org180454Identifier); } else { tgtItem.setReference("organism", taxItem.getIdentifier()); } LOG.debug("PROTEIN.PROTEIN_AC:" + srcItem.getAttribute("protein_ac").getValue() + " has tax_id:" + taxItem.getAttribute("taxa_id").getValue()); } else { LOG.warn("!!! PROTEIN.PROTEIN_AC:" + srcItem.getAttribute("protein_ac").getValue() + " has does NOT have a taxonomy object ref !!!"); } java.util.List matchesList = getItemsViaItemPath(srcItem, PROTEIN_FROM_MATCHES, srcItemReader); for (Iterator matchIt = matchesList.iterator(); matchIt.hasNext();) { org.intermine.xml.full.Item nextMatch = (org.intermine.xml.full.Item) matchIt.next(); org.intermine.xml.full.Reference methodRef = nextMatch.getReference(METHOD); org.intermine.xml.full.Item nextMethod = ItemHelper.convert(this.srcItemReader.getItemById(methodRef.getRefId())); addToCollection(tgtItem, PROTEINFEATURES, nextMethod); } java.util.List supermatchList = getItemsViaItemPath(srcItem, PROTEIN_FROM_SUPER_MATCH, srcItemReader); for (Iterator supermatchIt = supermatchList.iterator(); supermatchIt.hasNext();) { org.intermine.xml.full.Item nextSupermatch = (org.intermine.xml.full.Item) supermatchIt.next(); org.intermine.xml.full.Reference entryRef = nextSupermatch.getReference(ENTRY); org.intermine.xml.full.Item nextEntry = ItemHelper.convert(this.srcItemReader.getItemById(entryRef.getRefId())); addToCollection(tgtItem, PROTEINFEATURES, nextEntry); } Item extraDatabaseSynonym = createExtraDataSrcSynonym(interproDataSource, tgtItem, PRIMARYACCESSION); addReferencedItem(tgtItem, extraDatabaseSynonym, SYNONYMS, true, null, false); HashSet items = new HashSet(); items.add(extraDatabaseSynonym); return items; } private Set processMethodItem( org.intermine.xml.full.Item srcItem, org.intermine.xml.full.Item tgtItem) throws ObjectStoreException { //NOTE: This extended path only work as the bridge table has a 1 to 1 row count // with the method table. //HERE WE WANT TO ESTABLISH A LINK BETWEEN THE METHOD AND ITS RELATED INTERPRO_ID FROM THE // ENTRY TABLE org.intermine.xml.full.Item entryItem = getItemViaItemPath(srcItem, METHOD_TO_ENTRY_VIA_ENTRY_TO_METHOD, srcItemReader); if (entryItem != null) { //Get the interpro id for the related entry... org.intermine.xml.full.Attribute interproIdAttribute = new Attribute(); interproIdAttribute.setName("interproId"); interproIdAttribute.setValue(entryItem.getAttribute("entry_ac").getValue()); tgtItem.addAttribute(interproIdAttribute); //CHECK THE ENTRY RELATING TO THIS METHOD TO SEE IF IT IS A FAMILY OR AN EQIV DOMAIN... tryAndSetEntryTypeInAnEntry(entryItem); if (entryItem.getAttribute(ABBREV).getValue().equalsIgnoreCase(FAMILY)) { LOG.debug("SETTING METHOD AS PROTEINFAMILY ID:" + interproIdAttribute.getValue()); tgtItem.setClassName("http://www.flymine.org/model/genomic#ProteinFamily"); } else if (entryItem.getAttribute(ABBREV).getValue().equalsIgnoreCase(DOMAIN)) { LOG.debug("SETTING METHOD AS PROTEINDOMAIN ID:" + interproIdAttribute.getValue()); tgtItem.setClassName("http://www.flymine.org/model/genomic#ProteinDomain"); } else { LOG.debug("IGNORED AN METHOD-ENTRY MAPPING WITH TYPE:" + entryItem.getAttribute(ABBREV).getValue()); } } else { LOG.warn("METHOD WITH NO MAPPED ENTRY ITEM FOUND - " + "CHECK THE METHOD & ENTRY2METHOD & ENTRY TABLES!"); } //This extended path only work as the bridge table has a 1 to 1 row count with the // method table. //Here we want to fetch the evidence field that describes the relationship between the // method and entry items org.intermine.xml.full.Item cvEvidenceItem = getItemViaItemPath(srcItem, METHOD_TO_CV_EVIDENCE_VIA_ENTRY_TO_METHOD, srcItemReader); if (cvEvidenceItem != null) { addToCollection(tgtItem, EVIDENCE, cvEvidenceItem); //CHECK THE ENTRY RELATING TO THIS METHOD TO SEE IF IT IS A FAMILY OR AN EQUIVALENT DOMAIN. } else { LOG.warn("METHOD WITH NO MAPPED CV_EVIDENCE ITEM FOUND - " + "CHECK THE METHOD & ENTRY2METHOD & CV_EVIDENCE TABLES!"); } //Fill in the proteins collection which we can reach via the matches table... java.util.List matchesList = getItemsViaItemPath(srcItem, METHOD_FROM_MATCHES, srcItemReader); for (Iterator matchIt = matchesList.iterator(); matchIt.hasNext();) { org.intermine.xml.full.Item nextMatch = (org.intermine.xml.full.Item) matchIt.next(); org.intermine.xml.full.Reference proteinRef = nextMatch.getReference(PROTEIN); if (proteinRef != null) { org.intermine.xml.full.Item nextProtein = ItemHelper.convert(this.srcItemReader.getItemById(proteinRef.getRefId())); if (nextProtein != null) { if (nextProtein.hasAttribute(PROTEIN_AC)) { addToCollection(tgtItem, PROTEINS, nextProtein); } else { LOG.warn("METHOD-MATCHES-PROTEIN - PROTEIN_AC NOT FOUND!"); } } else { LOG.warn("METHOD-MATCHES-PROTEIN - NULL PROTEIN FROM REFERENCE!"); } } else { LOG.warn("METHOD WITH NO RELATED MATCHes FOUND!" + srcItem.getIdentifier()); } } { //Make sure that the target item has it's IDENTIFIER and NAME fields set... org.intermine.xml.full.Attribute methodAcAttribute = srcItem.getAttribute(METHOD_AC); org.intermine.xml.full.Attribute nuIdentifierAttribute = new org.intermine.xml.full.Attribute(); nuIdentifierAttribute.setName(IDENTIFIER); nuIdentifierAttribute.setValue(methodAcAttribute.getValue()); tgtItem.addAttribute(nuIdentifierAttribute); } { //Make sure that the target item has it's IDENTIFIER and NAME fields set... org.intermine.xml.full.Attribute nameAttribute = srcItem.getAttribute(NAME); org.intermine.xml.full.Attribute nuNameAttribute = new org.intermine.xml.full.Attribute(); nuNameAttribute.setName(NAME); nuNameAttribute.setValue(nameAttribute.getValue()); tgtItem.addAttribute(nuNameAttribute); } HashSet items = new HashSet(); if (tgtItem.hasAttribute("interproId")) { Item interproSynonym = createSynonym(tgtItem.getIdentifier(), IDENTIFIER, tgtItem.getAttribute("interproId").getValue(), interproDataSourceReference); addReferencedItem(tgtItem, interproSynonym, SYNONYMS, true, null, false); addToCollection(tgtItem, EVIDENCE, interproDataSet); items.add(interproSynonym); } Item extraDatabaseSynonym = createExtraDataSrcSynonym(interproDataSource, tgtItem, null); addReferencedItem(tgtItem, extraDatabaseSynonym, SYNONYMS, true, null, false); items.add(extraDatabaseSynonym); return items; } private Set processEntryItem( org.intermine.xml.full.Item srcItem, org.intermine.xml.full.Item tgtItem) throws ObjectStoreException { //Make sure that the entry object has a type !!! tryAndSetEntryTypeInAnEntry(srcItem); addToCollection(tgtItem, EVIDENCE, interproDataSet); //LINK ACCROSS THE SUPERMATCH BRIDGE TABLE TO SET THE RELATED // PROTEINS FOR THIS ENTRY/PROTEIN-DOMAIN/FAMILY java.util.List supermatchList = getItemsViaItemPath(srcItem, ENTRY_FROM_SUPER_MATCH, srcItemReader); for (Iterator supermatchIt = supermatchList.iterator(); supermatchIt.hasNext();) { org.intermine.xml.full.Item nextSuperMatch = (org.intermine.xml.full.Item) supermatchIt.next(); org.intermine.xml.full.Reference proteinRef = nextSuperMatch.getReference(PROTEIN); if (proteinRef != null) { org.intermine.xml.full.Item nextProtein = ItemHelper.convert(this.srcItemReader.getItemById(proteinRef.getRefId())); if (nextProtein != null) { if (nextProtein.hasAttribute(PROTEIN_AC)) { addToCollection(tgtItem, PROTEINS, nextProtein); } else { LOG.warn("ENTRY-SUPERMATCH-PROTEIN - PROTEIN_AC NOT FOUND!"); } } else { LOG.warn("ENTRY-SUPERMATCH-PROTEIN - NULL PROTEIN FROM REFERENCE!"); } } else { LOG.warn("ENTRY-SUPERMATCH-PROTEIN - NO REFERENCE TO ENTRY FOUND!"); } } //SET THE INTERPRO ACCESSION (ENTRY_AC) TO BE THE IDENTIFIER IN THE TGT ITEM if (tgtItem.hasAttribute(IDENTIFIER)) { LOG.debug("ENTRY HAS AN IDENTIFIER:" + tgtItem.getAttribute(IDENTIFIER).getValue()); } else { org.intermine.xml.full.Attribute srcEntryAcAttribute = srcItem.getAttribute(ENTRY_AC); if (srcEntryAcAttribute != null) { org.intermine.xml.full.Attribute tgtEntryAcAttribute = new Attribute(); tgtEntryAcAttribute.setName(IDENTIFIER); tgtEntryAcAttribute.setValue(srcEntryAcAttribute.getValue()); tgtItem.addAttribute(tgtEntryAcAttribute); } else { //unlikely - but you never know... LOG.warn("!!! ENTRY (identifier:" + (tgtItem.getAttribute(IDENTIFIER) != null ? tgtItem.getAttribute(IDENTIFIER).getValue() : "_NO_ID_FOUND_") + ") IS WITHOUT AN ENTRY_AC !!!"); } } //SET THE COMMENTS COLLECTION FROM THE COMMON_ANNOTATION TABLE. if (tgtItem.hasCollection(COMMENTS)) { LOG.debug("ENTRY WITH A COMMENTS LIST FOUND - SKIPPING COMMENT GENERATION"); } else { java.util.List entryToCommmonAnnotationList = getItemsViaItemPath( srcItem, ENTRY_FROM_ENTRY_TO_COMMON_ANNOTATION, srcItemReader); for (Iterator e2caIt = entryToCommmonAnnotationList.iterator(); e2caIt.hasNext();) { org.intermine.xml.full.Item nextE2CAItem = (org.intermine.xml.full.Item) e2caIt.next(); org.intermine.xml.full.Reference caRef = nextE2CAItem.getReference(COMMON_ANNOTATION); if (caRef != null) { org.intermine.xml.full.Item caItem = ItemHelper.convert(this.srcItemReader.getItemById(caRef.getRefId())); addToCollection(tgtItem, COMMENTS, caItem); } else { LOG.debug("ENTRY WITH NO COMMON_ANNOTATION OBJECT FOUND! " + nextE2CAItem.getIdentifier()); } } } //Link to the entry2entry & entry2comp tables to set PARENT/CHILD or EQUIVALENT relations. setupEntryRelations(ENTRY_FROM_ENTRY_TO_ENTRY_VIA_PARENT, srcItem, tgtItem, ENTRY, CHILDFEATURES); setupEntryRelations( ENTRY_FROM_ENTRY_TO_ENTRY_VIA_ENTRY, srcItem, tgtItem, PARENT, PARENTFEATURES); setupEntryRelations( ENTRY_FROM_ENTRY_TO_COMP_VIA_ENTRY_ONE, srcItem, tgtItem, ENTRY2, CONTAINS); setupEntryRelations( ENTRY_FROM_ENTRY_TO_COMP_VIA_ENTRY_TWO, srcItem, tgtItem, ENTRY1, FOUNDIN); Item interproSynonym = createSynonym(tgtItem.getIdentifier(), IDENTIFIER, tgtItem.getAttribute(IDENTIFIER).getValue(), interproDataSourceReference); addReferencedItem(tgtItem, interproSynonym, SYNONYMS, true, null, false); addToCollection(tgtItem, EVIDENCE, interproDataSet); HashSet items = new HashSet(); items.add(interproSynonym); return items; } private void processMatchesItem( org.intermine.xml.full.Item srcItem, org.intermine.xml.full.Item tgtItem) throws ObjectStoreException { //CHECK THAT THERE IS A REFERENCE TO THE CV_DATABASE ITEM FOR THIS MATCHES ITEM - // WARN IF NONE FOUND! org.intermine.xml.full.Reference cvdbRefSrc = srcItem.getReference(CV_DATABASE); if (cvdbRefSrc != null) { org.intermine.xml.full.Item cvdbItem = ItemHelper.convert(this.srcItemReader.getItemById(cvdbRefSrc.getRefId())); addToCollection(tgtItem, EVIDENCE, interproDataSet); } else { LOG.warn("!!! FOUND A MATCHES ITEM WITHOUT A REFERENCED CV_DATABASE ITEM !!!"); } //CHECK THAT THERE IS A REFERENCE TO THE CV_EVIDENCE ITEM FOR THIS MATCHES ITEM - // WARN IF NONE FOUND! org.intermine.xml.full.Reference cvevRefSrc = srcItem.getReference(CV_EVIDENCE); if (cvevRefSrc != null) { org.intermine.xml.full.Item cvevItem = ItemHelper.convert(this.srcItemReader.getItemById(cvevRefSrc.getRefId())); addToCollection(tgtItem, EVIDENCE, cvevItem); } else { LOG.warn("!!! FOUND A MATCHES ITEM WITHOUT A REFERENCED CV_EVIDENCE ITEM !!!"); } } private void processCommonAnnotationItem(org.intermine.xml.full.Item tgtItem) { tgtItem.setReference(SOURCE, interproDataSet.getIdentifier()); } /** * @param dataSrcItem - source database we are referencing * @param tgtItem - the Feature or Protein we are linking to * @param altAttrToUse - NULLABLE - if present try to use this instead of the IDENTIFIER attr. * */ private Item createExtraDataSrcSynonym(Item dataSrcItem, Item tgtItem, String altAttrToUse) { Item extraDatabaseSynonym = null; if (dataSrcItem != null && tgtItem != null) { //Do we want to use an attribute instead of the Identifier... if (altAttrToUse != null && tgtItem.hasAttribute(altAttrToUse)) { extraDatabaseSynonym = createSynonym( tgtItem.getIdentifier(), altAttrToUse, tgtItem.getAttribute(altAttrToUse).getValue(), new org.intermine.xml.full.Reference(SOURCE, dataSrcItem.getIdentifier())); } else if (tgtItem.hasAttribute(IDENTIFIER)) { extraDatabaseSynonym = createSynonym( tgtItem.getIdentifier(), IDENTIFIER, tgtItem.getAttribute(IDENTIFIER).getValue(), new org.intermine.xml.full.Reference(SOURCE, dataSrcItem.getIdentifier())); } else { LOG.warn("CAN'T CREATE SYNONYM FOR TGTITEM:" + tgtItem.getClassName() + " AS IT DOES NOT HAVE AN IDENTIFIER" + (altAttrToUse != null ? (" OR THIS ATTR:" + altAttrToUse) : "")); } } else { LOG.warn("SKIPPING SYNONYM CREATION FOR TGTITEM:" + (tgtItem != null ? tgtItem.getClassName() : "NULL")); } return extraDatabaseSynonym; } //Private helper method to assist in setting any reverse self relations in the // ProteinFamily object. private void setupEntryRelations( ItemPath familyFeatureItemPath, org.intermine.xml.full.Item srcItem, org.intermine.xml.full.Item tgtItem, String relationToMapTo, String targetCollectionName) throws ObjectStoreException { java.util.List familyList = getItemsViaItemPath(srcItem, familyFeatureItemPath, srcItemReader); if (familyList != null && familyList.size() > 0) { for (Iterator familyIterator = familyList.iterator(); familyIterator.hasNext();) { org.intermine.xml.full.Item relationshipItem = (org.intermine.xml.full.Item) familyIterator.next(); //check to see that the entry2xxxx item has a reference to the // cv_relation table so we can get it's type if (relationshipItem.hasReference(relationToMapTo)) { org.intermine.xml.full.Reference relativeRef = relationshipItem.getReference(relationToMapTo); org.intermine.xml.full.Item nextRelative = ItemHelper.convert( this.srcItemReader.getItemById(relativeRef.getRefId())); addToCollection(tgtItem, targetCollectionName, nextRelative); } else { LOG.warn("NO " + relationToMapTo + " RELATION FOUND FOR PATH" + familyFeatureItemPath.toString()); } } } } private Item createSynonym( String subjectId, String type, String value, org.intermine.xml.full.Reference ref) { Item synonym = createItem("Synonym"); synonym.addReference(new org.intermine.xml.full.Reference("subject", subjectId)); synonym.addAttribute(new Attribute("type", type)); synonym.addAttribute(new Attribute("value", value)); synonym.addReference(ref); return synonym; } /** * Factored this out so I can use it when I am not initially working on an entry item, but when * I am dealing with a protein via the supermatch table and need to make sure the entry_type is * set in the entry that the protein refers to so we can classify it as either a family or * domain and put into the correct collection for each protein... * <p/> * * @return a boolean indicating if we managed to set the entry_type or not... */ private boolean tryAndSetEntryTypeInAnEntry(org.intermine.xml.full.Item entry) throws ObjectStoreException { //Perhaps we've already set the type for this entry already... if (entry.hasAttribute(ABBREV)) { return true; } if (entry.getReference(CV_ENTRY_TYPE) != null) { org.intermine.xml.full.Reference cvetRef = entry.getReference(CV_ENTRY_TYPE); org.intermine.model.fulldata.Item cvetItem = this.srcItemReader.getItemById(cvetRef.getRefId()); Set cvetAttrSet = cvetItem.getAttributes(); Iterator cvetAttrIt = cvetAttrSet.iterator(); org.intermine.model.fulldata.Attribute cvetAttrNext; while (cvetAttrIt.hasNext()) { cvetAttrNext = (org.intermine.model.fulldata.Attribute) cvetAttrIt.next(); if (cvetAttrNext.getName().equalsIgnoreCase(ABBREV)) { org.intermine.xml.full.Attribute srcEntryTypeAttr = new Attribute(); srcEntryTypeAttr.setName(ABBREV); srcEntryTypeAttr.setValue(cvetAttrNext.getValue()); entry.addAttribute(srcEntryTypeAttr); return true; } } LOG.warn("!! DATA BUG - ENTRY WITH REFERENCE TO CV_ENTRY_TYPE WITH NO ABBREV FOUND !!"); return false; } else { LOG.warn("?? DATA BUG - ENTRY WITHOUT A REFERENCE TO A CV_ENTRY_TYPE OBJECT FOUND ??"); return false; } } /** * WE HAVE OVERRIDDEN THE PARENT METHOD TO SET THE BATCH SIZE TO A LOWER VALUE TO AVOID GETTING * TO MANY QUERY ITEMS * <p/> * Returns the Iterator over Items that the DataTranslator will translate. * * @return an Iterator * @throws ObjectStoreException if something goes wrong */ public Iterator getItemIterator() throws ObjectStoreException { //have to check this if we want our mock data tests to work... if (srcItemReader instanceof ObjectStoreItemReader) { ((ObjectStoreItemReader) srcItemReader).setBatchSize(500); } return srcItemReader.itemIterator(); } protected static final String PATH_NAME_SPACE = "http://www.intermine.org/model/interpro protected static final ItemPath TAXONOMY_FROM_PROTEIN = new ItemPath("(protein <- protein2taxonomy.protein).taxonomy", PATH_NAME_SPACE); protected static final ItemPath METHOD_TO_ENTRY_VIA_ENTRY_TO_METHOD = new ItemPath("(method <- entry2method.method).entry", PATH_NAME_SPACE); protected static final ItemPath METHOD_TO_CV_EVIDENCE_VIA_ENTRY_TO_METHOD = new ItemPath("(method <- entry2method.method).cv_evidence", PATH_NAME_SPACE); protected static final ItemPath ENTRY_VIA_ENTRY_TO_METHOD = new ItemPath("(entry <- entry2method.entry)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_ENTRY_TO_COMMON_ANNOTATION = new ItemPath("(entry <- entry2common_annotation.entry)", PATH_NAME_SPACE); protected static final ItemPath PROTEIN_FROM_MATCHES = new ItemPath("(protein <- matches.protein)", PATH_NAME_SPACE); protected static final ItemPath METHOD_FROM_MATCHES = new ItemPath("(method <- matches.method)", PATH_NAME_SPACE); protected static final ItemPath PROTEIN_FROM_SUPER_MATCH = new ItemPath("(protein <- supermatch.protein)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_SUPER_MATCH = new ItemPath("(entry <- supermatch.entry)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_ENTRY_TO_COMP_VIA_ENTRY_ONE = new ItemPath("(entry <- entry2comp.entry1)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_ENTRY_TO_COMP_VIA_ENTRY_TWO = new ItemPath("(entry <- entry2comp.entry2)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_ENTRY_TO_ENTRY_VIA_ENTRY = new ItemPath("(entry <- entry2entry.entry)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_FROM_ENTRY_TO_ENTRY_VIA_PARENT = new ItemPath("(entry <- entry2entry.parent)", PATH_NAME_SPACE); protected static final ItemPath ENTRY_TO_ENTRY_TO_CV_RELATION = new ItemPath("entry2entry.cv_relation", PATH_NAME_SPACE); protected static final ItemPath ENTRY_TO_COMP_TO_CV_RELATION = new ItemPath("entry2comp.cv_relation", PATH_NAME_SPACE); protected static final ItemPath DB_VERSION_TO_CV_DATABASE = new ItemPath("db_version.cv_database", PATH_NAME_SPACE); protected static final ItemPath CV_DATABASE_VIA_DB_VERSION = new ItemPath("(cv_database <- db_version.cv_database)", PATH_NAME_SPACE); /** * @return A map of all the interpro related prefetch descriptors. */ public static Map getPrefetchDescriptors() { Map paths = new HashMap(); { Set proteinSet = new HashSet(); proteinSet.add(TAXONOMY_FROM_PROTEIN.getItemPrefetchDescriptor()); ItemPrefetchDescriptor p2mDesc = new ItemPrefetchDescriptor("(protein <- matches.protein)"); p2mDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "protein")); p2mDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#matches", false)); ItemPrefetchDescriptor p2m2mDesc = new ItemPrefetchDescriptor("(protein <- matches.protein).method"); p2m2mDesc.addConstraint(new ItemPrefetchConstraintDynamic("method", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); p2mDesc.addPath(p2m2mDesc); proteinSet.add(p2mDesc); ItemPrefetchDescriptor p2smDesc = new ItemPrefetchDescriptor("(protein <- supermatch.protein)"); p2smDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "protein")); p2smDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#supermatch", false)); ItemPrefetchDescriptor p2sm2eDesc = new ItemPrefetchDescriptor("(protein <- supermatch.protein).entry"); p2sm2eDesc.addConstraint(new ItemPrefetchConstraintDynamic("entry", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); p2smDesc.addPath(p2sm2eDesc); proteinSet.add(p2smDesc); paths.put("http://www.intermine.org/model/interpro#protein", proteinSet); } { Set methodSet = new HashSet(); ItemPrefetchDescriptor m2cvdDesc = new ItemPrefetchDescriptor("(method.cv_database)"); m2cvdDesc.addConstraint(new ItemPrefetchConstraintDynamic("cv_database", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); methodSet.add(m2cvdDesc); ItemPrefetchDescriptor m2mDesc = new ItemPrefetchDescriptor("(method <- matches.method)"); m2mDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "method")); m2mDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#matches", false)); ItemPrefetchDescriptor m2m2pDesc = new ItemPrefetchDescriptor("(method <- matches.method).protein"); m2m2pDesc.addConstraint(new ItemPrefetchConstraintDynamic("protein", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); m2mDesc.addPath(m2m2pDesc); methodSet.add(m2mDesc); ItemPrefetchDescriptor m2e2eDesc = new ItemPrefetchDescriptor("(method <- entry2method.method)"); m2e2eDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "method")); m2e2eDesc.addConstraint(new FieldNameAndValue( ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2method", false)); ItemPrefetchDescriptor m2e2m2eDesc = new ItemPrefetchDescriptor("(method <- entry2method.method).entry"); m2e2m2eDesc.addConstraint(new ItemPrefetchConstraintDynamic("entry", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); m2e2eDesc.addPath(m2e2m2eDesc); ItemPrefetchDescriptor m2e2m2cveDesc = new ItemPrefetchDescriptor("(method <- entry2method.method).cv_evidence"); m2e2m2cveDesc.addConstraint(new ItemPrefetchConstraintDynamic("cv_evidence", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); m2e2eDesc.addPath(m2e2m2cveDesc); methodSet.add(m2e2eDesc); paths.put("http://www.intermine.org/model/interpro#method", methodSet); } { Set entrySet = getEntryPrefetchDescriptorSet(); paths.put("http://www.intermine.org/model/interpro#entry", entrySet); } { Set matchesSet = new HashSet(); ItemPrefetchDescriptor m2cvdbDesc = new ItemPrefetchDescriptor("(matches.cv_database)"); m2cvdbDesc.addConstraint(new ItemPrefetchConstraintDynamic("cv_database", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); matchesSet.add(m2cvdbDesc); ItemPrefetchDescriptor m2cvevDesc = new ItemPrefetchDescriptor("(matches.cv_evidence)"); m2cvevDesc.addConstraint(new ItemPrefetchConstraintDynamic("cv_evidence", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); matchesSet.add(m2cvevDesc); paths.put("http://www.intermine.org/model/interpro#matches", matchesSet); } { Set entry2entrySet = new HashSet(); entry2entrySet.add(ENTRY_TO_ENTRY_TO_CV_RELATION.getItemPrefetchDescriptor()); paths.put("http://www.intermine.org/model/interpro#entry2entry", entry2entrySet); } { Set entry2compSet = new HashSet(); entry2compSet.add(ENTRY_TO_COMP_TO_CV_RELATION.getItemPrefetchDescriptor()); paths.put("http://www.intermine.org/model/interpro#entry2comp", entry2compSet); } { Set dbVersionSet = new HashSet(); dbVersionSet.add(DB_VERSION_TO_CV_DATABASE.getItemPrefetchDescriptor()); paths.put("http://www.intermine.org/model/interpro#db_version", dbVersionSet); } { Set cvDatabaseSet = new HashSet(); cvDatabaseSet.add(CV_DATABASE_VIA_DB_VERSION.getItemPrefetchDescriptor()); ItemPrefetchDescriptor cvDbViaDbVerCvDbDesc = new ItemPrefetchDescriptor("(cv_database <- db_version.cv_database)"); cvDbViaDbVerCvDbDesc.addConstraint( new ItemPrefetchConstraintDynamic("cv_database", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); cvDatabaseSet.add(cvDbViaDbVerCvDbDesc); paths.put("http://www.intermine.org/model/interpro#cv_database", cvDatabaseSet); } return paths; } /** * @return A set of the prefetch descriptors related to the Entry source item. */ private static Set getEntryPrefetchDescriptorSet() { HashSet entrySet = new HashSet(); ItemPrefetchDescriptor e2cvetDesc = new ItemPrefetchDescriptor("(entry.cv_entry_type)"); e2cvetDesc.addConstraint(new ItemPrefetchConstraintDynamic("cv_entry_type", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); entrySet.add(e2cvetDesc); ItemPrefetchDescriptor e2cDesc = new ItemPrefetchDescriptor("(entry <- entry2common_annotation.entry)"); e2cDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry")); e2cDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2common_annotation", false)); ItemPrefetchDescriptor e2ec2cDesc = new ItemPrefetchDescriptor( "(entry <- entry2common_annotation.entry).common_annotation"); e2ec2cDesc.addConstraint(new ItemPrefetchConstraintDynamic("common_annotation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); e2cDesc.addPath(e2ec2cDesc); entrySet.add(e2cDesc); ItemPrefetchDescriptor e2e2mDesc = new ItemPrefetchDescriptor("(entry <- entry2method.entry)"); e2e2mDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry")); e2e2mDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2method", false)); ItemPrefetchDescriptor e2e2m2mDesc = new ItemPrefetchDescriptor("(entry <- entry2method.entry).method"); e2e2m2mDesc.addConstraint(new ItemPrefetchConstraintDynamic("method", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); e2e2mDesc.addPath(e2e2m2mDesc); entrySet.add(e2e2mDesc); ItemPrefetchDescriptor e2smDesc = new ItemPrefetchDescriptor("(entry <- supermatch.entry)"); e2smDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry")); e2smDesc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#supermatch", false)); ItemPrefetchDescriptor e2sm2pDesc = new ItemPrefetchDescriptor("(entry <- supermatch.entry).protein"); e2sm2pDesc.addConstraint(new ItemPrefetchConstraintDynamic("protein", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); e2smDesc.addPath(e2sm2pDesc); entrySet.add(e2smDesc); ItemPrefetchDescriptor eToe2cViaE1Desc = new ItemPrefetchDescriptor("(entry <- entry2comp.entry1)"); eToe2cViaE1Desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry1")); eToe2cViaE1Desc.addConstraint(new FieldNameAndValue( ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2comp", false)); ItemPrefetchDescriptor eToe2cViaE1ToE2Desc = new ItemPrefetchDescriptor("(entry <- entry2comp.entry1).entry2"); eToe2cViaE1ToE2Desc.addConstraint(new ItemPrefetchConstraintDynamic("entry2", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); eToe2cViaE1Desc.addPath(eToe2cViaE1ToE2Desc); entrySet.add(eToe2cViaE1Desc); ItemPrefetchDescriptor eToe2cViaE2Desc = new ItemPrefetchDescriptor("(entry <- entry2comp.entry2)"); eToe2cViaE2Desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry2")); eToe2cViaE2Desc.addConstraint(new FieldNameAndValue( ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2comp", false)); ItemPrefetchDescriptor eToe2cViaE2ToE1Desc = new ItemPrefetchDescriptor("(entry <- entry2comp.entry2).entry1"); eToe2cViaE2ToE1Desc.addConstraint(new ItemPrefetchConstraintDynamic("entry1", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); eToe2cViaE2Desc.addPath(eToe2cViaE2ToE1Desc); entrySet.add(eToe2cViaE2Desc); ItemPrefetchDescriptor eToe2eViaEDesc = new ItemPrefetchDescriptor("(entry <- entry2entry.entry)"); eToe2eViaEDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "entry")); eToe2eViaEDesc.addConstraint(new FieldNameAndValue( ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2entry", false)); ItemPrefetchDescriptor eToe2eViaEToPDesc = new ItemPrefetchDescriptor("(entry <- entry2entry.entry).parent"); eToe2eViaEToPDesc.addConstraint(new ItemPrefetchConstraintDynamic("parent", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); eToe2eViaEDesc.addPath(eToe2eViaEToPDesc); entrySet.add(eToe2eViaEDesc); ItemPrefetchDescriptor eToe2eViaPDesc = new ItemPrefetchDescriptor("(entry <- entry2entry.parent)"); eToe2eViaPDesc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "parent")); eToe2eViaPDesc.addConstraint(new FieldNameAndValue( ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.intermine.org/model/interpro#entry2entry", false)); ItemPrefetchDescriptor eToe2eViaPToEDesc = new ItemPrefetchDescriptor("(entry <- entry2entry.parent).entry"); eToe2eViaPToEDesc.addConstraint(new ItemPrefetchConstraintDynamic("entry", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); eToe2eViaPDesc.addPath(eToe2eViaPToEDesc); entrySet.add(eToe2eViaPDesc); return entrySet; } /** * Holds a datasource item & a manual count of how many times the item has been used. * */ class DataSourceAndSetUsageCounter { private Item dataSource; private Item dataSet; private int sourceUseageCount; /** * @param dataSource - the source db item to count for. * @param dataSet - the related dataset item. * */ DataSourceAndSetUsageCounter(Item dataSource, Item dataSet) { this.dataSource = dataSource; this.dataSet = dataSet; sourceUseageCount = 0; } /** * @return The datasource item that we are counting for. * */ synchronized Item getDataSource() { sourceUseageCount++; return dataSource; } /** * @return The dataset item that is related to the datasource item. * */ public Item getDataSet() { return dataSet; } /** * @return the current value of our usage counter. * */ synchronized int getSourceUseageCount() { return sourceUseageCount; } } }
package com.bluesnap.androidapi.views.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.*; import com.bluesnap.androidapi.R; import com.bluesnap.androidapi.models.StateListObject; import com.bluesnap.androidapi.services.BlueSnapValidator; import com.bluesnap.androidapi.views.adapters.StateListAdapter; import java.util.*; public class StateActivity extends Activity { ListView listView; String[] state_values_array; String[] state_key_array; EditText inputSearch; String localeState; StateListAdapter adapter; Map<String, Integer> mapIndex; private final TextWatcher searchLineTextWatcher = new SearchLineTextWatcher(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bluesnap_state_selector); final ImageButton backButton = findViewById(R.id.back_button); inputSearch = findViewById(R.id.searchView); listView = findViewById(R.id.state_list_view); savedInstanceState = getIntent().getExtras(); if (savedInstanceState != null) { String countryString = savedInstanceState.getString(getString(R.string.COUNTRY_STRING)); countryString = countryString == null ? "" : countryString.toUpperCase(); String stateString = savedInstanceState.getString(getString(R.string.STATE_STRING)); stateString = stateString == null ? "" : stateString.toUpperCase(); // check if US, BlueSnapValidator.STATE_NEEDED_COUNTRIES[0] = US if (countryString.equals(BlueSnapValidator.STATE_NEEDED_COUNTRIES[0])) { state_values_array = getResources().getStringArray(R.array.state_us_value_array); state_key_array = getResources().getStringArray(R.array.state_us_key_array); } else if (countryString.equals(BlueSnapValidator.STATE_NEEDED_COUNTRIES[1])) { // check if BR, BlueSnapValidator.STATE_NEEDED_COUNTRIES[1] = BR state_values_array = getResources().getStringArray(R.array.state_br_value_array); state_key_array = getResources().getStringArray(R.array.state_br_key_array); } else { // check if CA, BlueSnapValidator.STATE_NEEDED_COUNTRIES[2] = CA state_values_array = getResources().getStringArray(R.array.state_ca_value_array); state_key_array = getResources().getStringArray(R.array.state_ca_key_array); } Integer index = !"".equals(stateString) ? Arrays.asList(state_key_array).indexOf(stateString) : -1; localeState = index != -1 ? state_values_array[index] : ""; } adapter = new StateListAdapter(this, StateListObject.getStateListObject(state_values_array, state_key_array), localeState); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String statePick = adapter.stateListObjects.get(position).getStateCode(); Intent returnIntent = new Intent(); returnIntent.putExtra("result", statePick); setResult(Activity.RESULT_OK, returnIntent); finish(); } }); getIndexList(state_values_array); displayIndex(); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); inputSearch.addTextChangedListener(searchLineTextWatcher); } private void getIndexList(String[] lists) { mapIndex = new LinkedHashMap<>(); for (int i = 0; i < lists.length; i++) { String list = lists[i]; String index = list.substring(0, 1); if (mapIndex.get(index) == null) mapIndex.put(index, i); } } private void displayIndex() { LinearLayout indexLayout = findViewById(R.id.side_index); TextView textView; List<String> indexList = new ArrayList<>(mapIndex.keySet()); for (String index : indexList) { textView = (TextView) getLayoutInflater().inflate( R.layout.side_index_item, null); textView.setText(index); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TextView selectedIndex = (TextView) view; listView.setSelection(mapIndex.get(selectedIndex.getText().toString())); } }); indexLayout.addView(textView); } } private class SearchLineTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence cs, int start, int count, int after) { } @Override public void onTextChanged(CharSequence cs, int start, int before, int count) { adapter.getFilter().filter(cs); } @Override public void afterTextChanged(Editable s) { } } }
package es.fhir.rest.core.transformer; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; import org.osgi.service.component.annotations.Component; import ca.uhn.fhir.model.dstu2.composite.HumanNameDt; import ca.uhn.fhir.model.dstu2.composite.IdentifierDt; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum; import ca.uhn.fhir.model.primitive.DateDt; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.UriDt; import ch.elexis.core.types.Gender; import es.fhir.rest.core.IFhirTransformer; import info.elexis.server.core.connector.elexis.jpa.model.annotated.Kontakt; @Component public class PatientKontaktTransformer implements IFhirTransformer<Patient, Kontakt> { @Override public Patient getFhirObject(Kontakt localObject) { Patient patient = new Patient(); patient.setId(new IdDt("Patient", localObject.getId())); String patNr = localObject.getPatientNr(); IdentifierDt elexisId = patient.addIdentifier(); elexisId.setSystem(new UriDt("www.elexis.info/patnr")); elexisId.setValue(patNr); elexisId = patient.addIdentifier(); elexisId.setSystem(new UriDt("www.elexis.info/objid")); elexisId.setValue(localObject.getId()); HumanNameDt patName = patient.addName(); patName.addFamily(localObject.getFamilyName()); patName.addGiven(localObject.getFirstName()); patName.addPrefix(localObject.getTitel()); patName.addSuffix(localObject.getTitelSuffix()); if (localObject.getGender() == Gender.FEMALE) { patient.setGender(AdministrativeGenderEnum.FEMALE); } else if (localObject.getGender() == Gender.MALE) { patient.setGender(AdministrativeGenderEnum.MALE); } else if (localObject.getGender() == Gender.UNDEFINED) { patient.setGender(AdministrativeGenderEnum.OTHER); } else { patient.setGender(AdministrativeGenderEnum.UNKNOWN); } LocalDate dateOfBirth = localObject.getDob(); if (dateOfBirth != null) { patient.setBirthDate(new DateDt(Date.from(dateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant()))); } return patient; } @Override public Kontakt getLocalObject(Patient fhirObject) { // TODO Auto-generated method stub return null; } @Override public boolean matchesTypes(Class<?> fhirClazz, Class<?> localClazz) { return Patient.class.equals(fhirClazz) && Kontakt.class.equals(localClazz); } }
package com.dianping.cat.consumer.build; import java.util.ArrayList; import java.util.List; import org.unidal.cat.config.internal.DBConfigManager; import org.unidal.cat.plugin.event.EventPipeline; import org.unidal.cat.plugin.transaction.TransactionAllReportMaker; import org.unidal.cat.plugin.transaction.TransactionConfigProvider; import org.unidal.cat.plugin.transaction.TransactionPipeline; import org.unidal.lookup.configuration.AbstractResourceConfigurator; import org.unidal.lookup.configuration.Component; import com.dianping.cat.service.ProjectService; public class Cat2ComponentsConfigurator extends AbstractResourceConfigurator { @Override public List<Component> defineComponents() { List<Component> all = new ArrayList<Component>(); all.add(A(TransactionPipeline.class)); all.add(A(TransactionAllReportMaker.class)); all.add(A(EventPipeline.class)); all.add(A(TransactionConfigProvider.class)); all.add(A(DBConfigManager.class)); all.add(A(ProjectService.class)); return all; } }
package org.jpos.iso; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; public class ISOCurrency { private static final Map<String, Currency> currencies = new HashMap<String, Currency>(); // Avoid creation of instances. private ISOCurrency() { } static { addJavaCurrencies(); loadPropertiesFromClasspath("org/jpos/iso/ISOCurrency.properties"); loadPropertiesFromClasspath("META-INF/org/jpos/config/ISOCurrency.properties"); } private static void addJavaCurrencies() { List<java.util.Currency> currencies = java.util.Currency.getAvailableCurrencies() .stream() .sorted(Comparator.comparing(java.util.Currency::getCurrencyCode)) .collect(Collectors.toList()); for (java.util.Currency sc : currencies) { try { addCurrency(sc.getCurrencyCode().toUpperCase(), ISOUtil.zeropad(Integer.toString(sc.getNumericCode()), 3), sc.getDefaultFractionDigits()); } catch (ISOException ignored) { } } } @SuppressWarnings({"EmptyCatchBlock"}) public static void loadPropertiesFromClasspath(String base) { InputStream in=loadResourceAsStream(base); try { if(in!=null) { addBundle(new PropertyResourceBundle(in)); } } catch (IOException e) { } finally { if(in!=null) { try { in.close(); } catch (IOException e) { } } } } public static double convertFromIsoMsg(String isoamount, String currency) throws IllegalArgumentException { Currency c = findCurrency(currency); return c.parseAmountFromISOMsg(isoamount); } public static String toISO87String (BigDecimal amount, String currency) { try { Currency c = findCurrency(currency); return ISOUtil.zeropad(amount.movePointRight(c.getDecimals()).setScale(0).toPlainString(), 12); } catch (ISOException e) { throw new IllegalArgumentException("Failed to convert amount",e); } } public static BigDecimal parseFromISO87String (String isoamount, String currency) { int decimals = findCurrency(currency).getDecimals(); return new BigDecimal(isoamount).movePointLeft(decimals); } public static void addBundle(String bundleName) { ResourceBundle r = ResourceBundle.getBundle(bundleName); addBundle(r); } public static String convertToIsoMsg(double amount, String currency) throws IllegalArgumentException { return findCurrency(currency).formatAmountForISOMsg(amount); } public static Object[] decomposeComposedCurrency(String incurr) throws IllegalArgumentException { final String[] strings = incurr.split(" "); if (strings.length != 2) { throw new IllegalArgumentException("Invalid parameter: " + incurr); } return new Object[]{strings[0], Double.valueOf(strings[1])}; } public static String getIsoCodeFromAlphaCode(String alphacode) throws IllegalArgumentException { try { Currency c = findCurrency(alphacode); return ISOUtil.zeropad(Integer.toString(c.getIsoCode()), 3); } catch (ISOException e) { throw new IllegalArgumentException("Failed getIsoCodeFromAlphaCode/ zeropad failed?", e); } } public static Currency getCurrency(int code) throws ISOException { final String isoCode = ISOUtil.zeropad(Integer.toString(code), 3); return findCurrency(isoCode); } public static Currency getCurrency(String code) throws ISOException { final String isoCode = ISOUtil.zeropad(code, 3); return findCurrency(isoCode); } private static InputStream loadResourceAsStream(String name) { InputStream in = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { in = contextClassLoader.getResourceAsStream(name); } if (in == null) { in = ISOCurrency.class.getClassLoader().getResourceAsStream(name); } return in; } /** * Should be called like this: put("ALL", "008", 2); * Note: the second parameter is zero padded to three digits * * @param alphaCode An alphabetic code such as USD * @param isoCode An ISO code such as 840 * @param numDecimals the number of implied decimals */ private static void addCurrency(String alphaCode, String isoCode, int numDecimals) { // to allow a clean replacement from a more specific resource bundle we // require clearing instead of overriding. if(currencies.containsKey(alphaCode) || currencies.containsKey(isoCode)) { currencies.remove(alphaCode); currencies.remove(isoCode); } Currency ccy = new Currency(alphaCode, Integer.parseInt(isoCode), numDecimals); currencies.put(alphaCode, ccy); currencies.put(isoCode, ccy); } private static Currency findCurrency(String currency) { final Currency c = currencies.get(currency.toUpperCase()); if (c == null) { throw new IllegalArgumentException("Currency with key '" + currency + "' was not found"); } return c; } private static void addBundle(ResourceBundle r) { Enumeration en = r.getKeys(); while (en.hasMoreElements()) { String alphaCode = (String) en.nextElement(); String[] tmp = r.getString(alphaCode).split(" "); String isoCode = tmp[0]; int numDecimals = Integer.parseInt(tmp[1]); addCurrency(alphaCode, isoCode, numDecimals); } } }
package me.lucko.luckperms.common.plugin.scheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Abstract implementation of {@link SchedulerAdapter} using a {@link ScheduledExecutorService}. */ public abstract class AbstractJavaScheduler implements SchedulerAdapter { private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("luckperms-scheduler") .build() ); private final ErrorReportingExecutor workerPool = new ErrorReportingExecutor(Executors.newCachedThreadPool(new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("luckperms-worker-%d") .build() )); @Override public Executor async() { return this.workerPool; } @Override public SchedulerTask asyncLater(Runnable task, long delay, TimeUnit unit) { ScheduledFuture<?> future = this.scheduler.schedule(() -> this.workerPool.execute(task), delay, unit); return () -> future.cancel(false); } @Override public SchedulerTask asyncRepeating(Runnable task, long interval, TimeUnit unit) { ScheduledFuture<?> future = this.scheduler.scheduleAtFixedRate(() -> this.workerPool.execute(task), interval, interval, unit); return () -> future.cancel(false); } @Override public void shutdown() { this.scheduler.shutdown(); this.workerPool.delegate.shutdown(); try { this.workerPool.delegate.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } } private static final class ErrorReportingExecutor implements Executor { private final ExecutorService delegate; private ErrorReportingExecutor(ExecutorService delegate) { this.delegate = delegate; } @Override public void execute(@NonNull Runnable command) { this.delegate.execute(new ErrorReportingRunnable(command)); } } private static final class ErrorReportingRunnable implements Runnable { private final Runnable delegate; private ErrorReportingRunnable(Runnable delegate) { this.delegate = delegate; } @Override public void run() { try { this.delegate.run(); } catch (Exception e) { e.printStackTrace(); } } } }
package org.neo4j.server.rest.repr.formats; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.impl.Utf8Generator; import org.codehaus.jackson.io.IOContext; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.neo4j.helpers.Service; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.server.rest.domain.JsonHelper; import org.neo4j.server.rest.domain.JsonParseException; import org.neo4j.server.rest.repr.BadInputException; import org.neo4j.server.rest.repr.DefaultFormat; import org.neo4j.server.rest.repr.InputFormat; import org.neo4j.server.rest.repr.ListWriter; import org.neo4j.server.rest.repr.MappingWriter; import org.neo4j.server.rest.repr.RepresentationFormat; import org.neo4j.server.rest.repr.StreamingFormat; @Service.Implementation( RepresentationFormat.class ) public class StreamingJsonFormat extends RepresentationFormat implements StreamingFormat { public static final MediaType MEDIA_TYPE = new MediaType( MediaType.APPLICATION_JSON_TYPE.getType(), MediaType.APPLICATION_JSON_TYPE.getSubtype(), MapUtil.stringMap( "stream", "true" ) ); private final JsonFactory factory; public StreamingJsonFormat() { super(MEDIA_TYPE); this.factory = createJsonFactory(); } private JsonFactory createJsonFactory() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.getSerializationConfig().disable(SerializationConfig.Feature.FLUSH_AFTER_WRITE_VALUE); JsonFactory factory = new JsonFactory(objectMapper) { @Override protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException { final int bufferSize = 1024 * 8; Utf8Generator gen = new Utf8Generator(ctxt, _generatorFeatures, _objectCodec, out,new byte[bufferSize],0,true); if (_characterEscapes != null) { gen.setCharacterEscapes(_characterEscapes); } return gen; } }; factory.enable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM); return factory; } @Override public StreamingRepresentationFormat writeTo(OutputStream output) { try { final JsonGenerator g = factory.createJsonGenerator(output); return new StreamingRepresentationFormat(g,this); } catch (IOException e) { throw new WebApplicationException( e ); } } @Override protected ListWriter serializeList(String type) { throw new UnsupportedOperationException(); } @Override protected String complete( ListWriter serializer ) { throw new UnsupportedOperationException(); } @Override protected MappingWriter serializeMapping( String type ) { throw new UnsupportedOperationException(); } @Override protected String complete( MappingWriter serializer ) { throw new UnsupportedOperationException(); } @Override protected String serializeValue( String type, Object value ) { throw new UnsupportedOperationException(); } private boolean empty( String input ) { return input == null || "".equals( input.trim() ); } @Override public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException { if ( empty( input ) ) return DefaultFormat.validateKeys( Collections.<String,Object>emptyMap(), requiredKeys ); try { return DefaultFormat.validateKeys( JsonHelper.jsonToMap( stripByteOrderMark( input ) ), requiredKeys ); } catch ( JsonParseException ex ) { throw new BadInputException( ex ); } } @Override public List<Object> readList( String input ) { // TODO tobias: Implement readList() [Dec 10, 2010] throw new UnsupportedOperationException( "Not implemented: JsonInput.readList()" ); } @Override public Object readValue( String input ) throws BadInputException { if ( empty( input ) ) return Collections.emptyMap(); try { return JsonHelper.jsonToSingleValue( stripByteOrderMark( input ) ); } catch ( JsonParseException ex ) { throw new BadInputException( ex ); } } @Override public URI readUri( String input ) throws BadInputException { try { return new URI( readValue( input ).toString() ); } catch ( URISyntaxException e ) { throw new BadInputException( e ); } } private String stripByteOrderMark( String string ) { if ( string != null && string.length() > 0 && string.charAt( 0 ) == 0xfeff ) { return string.substring( 1 ); } return string; } private static class StreamingMappingWriter extends MappingWriter { private final JsonGenerator g; public StreamingMappingWriter(JsonGenerator g) { this.g = g; try { g.writeStartObject(); } catch (IOException e) { throw new WebApplicationException(e); } } public StreamingMappingWriter(JsonGenerator g, String key) { this.g = g; try { g.writeObjectFieldStart(key); } catch (IOException e) { throw new WebApplicationException(e); } } @Override public MappingWriter newMapping(String type, String key) { return new StreamingMappingWriter(g,key); } @Override public ListWriter newList(String type, String key) { return new StreamingListWriter(g,key); } @Override public void writeValue(String type, String key, Object value) { try { g.writeObjectField(key, value); // todo individual fields } catch (IOException e) { throw new WebApplicationException(e); } } @Override public void done() { try { g.writeEndObject(); } catch (IOException e) { throw new WebApplicationException(e); } } } private static class StreamingListWriter extends ListWriter { private final JsonGenerator g; public StreamingListWriter(JsonGenerator g) { this.g = g; try { g.writeStartArray(); } catch (IOException e) { throw new WebApplicationException(e); } } public StreamingListWriter(JsonGenerator g, String key) { this.g = g; try { g.writeArrayFieldStart(key); } catch (IOException e) { throw new WebApplicationException(e); } } @Override public MappingWriter newMapping(String type) { return new StreamingMappingWriter(g); } @Override public ListWriter newList(String type) { return new StreamingListWriter(g); } @Override public void writeValue(String type, Object value) { try { g.writeObject(value); } catch (IOException e) { throw new WebApplicationException(e); } } @Override public void done() { try { g.writeEndArray(); } catch (IOException e) { throw new WebApplicationException(e); } } } public static class StreamingRepresentationFormat extends RepresentationFormat { private final JsonGenerator g; private final InputFormat inputFormat; public StreamingRepresentationFormat(JsonGenerator g, InputFormat inputFormat) { super(StreamingJsonFormat.MEDIA_TYPE); this.g = g; this.inputFormat = inputFormat; } public StreamingRepresentationFormat usePrettyPrinter() { g.useDefaultPrettyPrinter(); return this; } @Override protected String serializeValue(String type, Object value) { try { g.writeObject(value); return null; } catch (IOException e) { throw new WebApplicationException(e); } } @Override protected ListWriter serializeList(String type) { return new StreamingListWriter(g); } @Override public MappingWriter serializeMapping(String type) { return new StreamingMappingWriter(g); } @Override protected String complete(ListWriter serializer) { flush(); return null; // already done in done() } @Override protected String complete(MappingWriter serializer) { flush(); return null; // already done in done() } private void flush() { try { g.flush(); } catch (IOException e) { throw new WebApplicationException(e); } } @Override public Object readValue(String input) throws BadInputException { return inputFormat.readValue(input); } @Override public Map<String, Object> readMap(String input, String... requiredKeys) throws BadInputException { return inputFormat.readMap(input, requiredKeys); } @Override public List<Object> readList(String input) throws BadInputException { return inputFormat.readList(input); } @Override public URI readUri(String input) throws BadInputException { return inputFormat.readUri(input); } @Override public void complete() { try { // todo only if needed g.flush(); } catch (IOException e) { throw new WebApplicationException(e); } } } }
/* * (e-mail:zhongxunking@163.com) */ /* * : * @author 2017-09-11 14:53 */ package org.antframework.configcenter.client; import org.antframework.common.util.other.Cache; import org.antframework.configcenter.client.support.RefreshTrigger; import org.antframework.configcenter.client.support.ServerRequester; import org.antframework.configcenter.client.support.TaskExecutor; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.Collections; import java.util.Set; import java.util.function.Function; public class ConfigsContext { // config private final Cache<String, Config> configsCache = new Cache<>(new Function<String, Config>() { @Override public Config apply(String appId) { Config config = new Config(appId, serverRequester, cacheDirPath); if (refreshTrigger != null) { refreshTrigger.addApp(appId); } return config; } }); private final TaskExecutor taskExecutor = new TaskExecutor(); private final ServerRequester serverRequester; private final String profileId; // null private final String cacheDirPath; private RefreshTrigger refreshTrigger; /** * * * @param serverUrl * @param mainAppId id * @param profileId id * @param cacheDirPath null */ public ConfigsContext(String serverUrl, String mainAppId, String profileId, String cacheDirPath) { if (StringUtils.isBlank(serverUrl) || StringUtils.isBlank(mainAppId) || StringUtils.isBlank(profileId)) { throw new IllegalArgumentException(String.format("serverUrl=%s,mainAppId=%s,profileId=%s,cacheDirPath=%s", serverUrl, mainAppId, profileId, cacheDirPath)); } serverRequester = new ServerRequester(serverUrl, mainAppId, profileId); this.profileId = profileId; this.cacheDirPath = cacheDirPath == null ? null : cacheDirPath + File.separator + mainAppId + File.separator + profileId; } /** * * * @param appId id * @return */ public Config getConfig(String appId) { return configsCache.get(appId); } public synchronized void listenConfigs() { if (refreshTrigger != null) { return; } refreshTrigger = new RefreshTrigger(profileId, serverRequester, this::refreshConfig, cacheDirPath); for (String appId : getAppIds()) { refreshTrigger.addApp(appId); } } /** * zookeeper */ public void refresh() { for (String appId : getAppIds()) { refreshConfig(appId); if (refreshTrigger != null) { refreshTrigger.addApp(appId); } } if (refreshTrigger != null) { taskExecutor.execute(new TaskExecutor.Task<RefreshTrigger>(refreshTrigger) { @Override protected void doRun(RefreshTrigger target) { target.refreshZk(); } }); } } public Set<String> getAppIds() { return Collections.unmodifiableSet(configsCache.getAllKeys()); } public synchronized void close() { if (refreshTrigger != null) { refreshTrigger.close(); } taskExecutor.close(); } private void refreshConfig(String appId) { taskExecutor.execute(new TaskExecutor.Task<Config>(configsCache.get(appId)) { @Override protected void doRun(Config target) { target.refresh(); } }); } }
package org.ednovo.gooru.converter.service; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; import org.ednovo.gooru.application.converter.ConversionAppConstants; import org.ednovo.gooru.application.converter.GooruImageUtil; import org.ednovo.gooru.application.converter.PdfToImageRenderer; import org.ednovo.gooru.converter.controllers.Conversion; import org.ednovo.gooru.kafka.KafkaProducer; import org.jets3t.service.acl.AccessControlList; import org.jets3t.service.acl.GroupGrantee; import org.jets3t.service.acl.Permission; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Object; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.restlet.resource.ClientResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.code.javascribd.connection.ScribdClient; import com.google.code.javascribd.connection.StreamableData; import com.google.code.javascribd.docs.Upload; import com.google.code.javascribd.type.Access; import com.google.code.javascribd.type.ApiKey; import com.google.code.javascribd.type.FileData; import flexjson.JSONSerializer; @Service public class ConversionServiceImpl implements ConversionService, ConversionAppConstants { private static final Logger logger = LoggerFactory.getLogger(GooruImageUtil.class); @Autowired @javax.annotation.Resource(name = "contentS3Service") private RestS3Service s3Service; @Autowired private KafkaProducer kafkaProducer; @Override public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { return resizeImageByDimensions(srcFilePath, targetFolderPath, null, dimensions, resourceGooruOid, sessionToken, thumbnail, apiEndPoint); } @Override public void scribdUpload(String apiKey, String dockey, String filepath, String gooruOid, String authXml) { ScribdClient client = new ScribdClient(); ApiKey apikey = new ApiKey(apiKey); File file = new File(filepath); StreamableData uploadData = new FileData(file); // initialize upload method Upload upload = new Upload(apikey, uploadData); upload.setDocType(PDF); upload.setAccess(Access.PRIVATE); upload.setRevId(new Integer(dockey)); try { client.execute(upload); } catch (Exception e) { logger.info("$ Textbook upload failed ", e); } try { File srcFile = new File(filepath); new PdfToImageRenderer().process(filepath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } @Override public void resizeImage(String command, String logFile) { logger.info("Runtime Executor .... Initializing..."); try { command = StringUtils.replace(command, "/usr/bin/convert", "/usr/bin/gm@convert"); String cmdArgs[] = applyTemporaryFixForPath(command.split("@")); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); if (logFile != null) { FileUtils.writeStringToFile(new File(logFile), "Completed"); } } catch (Exception e) { logger.error("something went wrong while converting image", e); } } private static String[] applyTemporaryFixForPath(String[] cmdArgs) { if (cmdArgs.length > 0) { String[] fileTypes = { ".jpeg", ".JPEG", ".jpg", ".JPG", ".png", ".PNG", ".gif", ".GIF" }; for (int argIndex = 0; argIndex < cmdArgs.length; argIndex++) { String part = cmdArgs[argIndex]; if (containsIgnoreCaseInArray(part, fileTypes)) { String filePath = null; String repoPath = StringUtils.substringBeforeLast(part, "/"); String remainingPart = StringUtils.substringAfter(part, "/"); for (String fileType : fileTypes) { filePath = StringUtils.substringAfter(remainingPart, fileType); if (!filePath.isEmpty()) { break; } } if (!filePath.isEmpty()) { if (!repoPath.isEmpty()) { filePath = repoPath + "/" + filePath; } cmdArgs[argIndex] = filePath; } } } } return cmdArgs; } private static boolean containsIgnoreCaseInArray(String haystack, String[] containsArray) { for (String key : containsArray) { if (haystack.contains(key)) { return true; } } return false; } @Override public void convertPdfToImage(String resourceFilePath, String gooruOid, String authXml) { logger.warn("$ Processing pdf slides conversion request for : " + resourceFilePath); try { File srcFile = new File(resourceFilePath); new PdfToImageRenderer().process(resourceFilePath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String filenamePrefix, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { String imagePath = null; List<String> list = new ArrayList<String>(); try { logger.debug(" src : {} /= target : {}", srcFilePath, targetFolderPath); String[] imageDimensions = dimensions.split(","); if (filenamePrefix == null) { filenamePrefix = StringUtils.substringAfterLast(srcFilePath, "/"); if (filenamePrefix.contains(".")) { filenamePrefix = StringUtils.substringBeforeLast(filenamePrefix, "."); } } for (String dimension : imageDimensions) { String[] xy = dimension.split(X); int width = Integer.valueOf(xy[0]); int height = Integer.valueOf(xy[1]); imagePath = resizeImageByDimensions(srcFilePath, width, height, targetFolderPath + filenamePrefix + "-" + dimension + "." + getFileExtenstion(srcFilePath)); list.add(imagePath); } try { JSONObject json = new JSONObject(); json.put(RESOURCE_GOORU_OID, resourceGooruOid); json.put(THUMBNAIL, thumbnail); JSONObject jsonAlias = new JSONObject(); jsonAlias.put(MEDIA, json); String jsonString = jsonAlias.toString(); StringRequestEntity requestEntity = new StringRequestEntity(jsonString, APP_JSON, "UTF-8"); HttpClient client = new HttpClient(); PostMethod postmethod = new PostMethod(apiEndPoint + "/media/resource/thumbnail?sessionToken=" + sessionToken); postmethod.setRequestEntity(requestEntity); client.executeMethod(postmethod); } catch (Exception ex) { logger.error("rest api call failed!", ex.getMessage()); } } catch (Exception ex) { logger.error("Multiple scaling of image failed for src : " + srcFilePath + " : ", ex); } return list; } public String resizeImageByDimensions(String srcFilePath, int width, int height, String destFilePath) throws Exception { String imagePath = null; try { logger.debug(" src : {} /= target : {}", srcFilePath, destFilePath); File destFile = new File(destFilePath); if (new File(srcFilePath).exists() && destFile.exists()) { destFile.delete(); } scaleImageUsingImageMagick(srcFilePath, width, height, destFilePath); imagePath = destFile.getPath(); } catch (Exception ex) { logger.error("Error while scaling image", ex); throw ex; } return imagePath; } public void scaleImageUsingImageMagick(String srcFilePath, int width, int height, String destFilePath) throws Exception { try { String resizeCommand = new String("/usr/bin/gm@convert@" + srcFilePath + "@-resize@" + width + X + height + "@" + destFilePath); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); } catch (Exception e) { logger.error("something went wrong while converting image", e); } } @Override public String convertHtmlToPdf(String htmlContent, String targetPath, String sourceHtmlUrl, String filename) { File targetDir = new File(targetPath); if (!targetDir.exists()) { targetDir.mkdirs(); } if (filename == null) { filename = String.valueOf(System.currentTimeMillis()); } else { File file = new File(targetPath + filename + DOT_PDF); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis(); } } if (htmlContent != null) { if (saveAsHtml(targetPath + filename + DOT_HTML, htmlContent) != null) { convertHtmlToPdf(targetPath + filename + DOT_HTML, targetPath + filename + DOT_PDF, 0); File file = new File(targetPath + filename + DOT_HTML); file.delete(); return filename + DOT_PDF; } } else if (sourceHtmlUrl != null) { convertHtmlToPdf(sourceHtmlUrl, targetPath + filename + DOT_PDF, 30000); return filename + DOT_PDF; } return null; } private static String saveAsHtml(String fileName, String content) { File file = new File(fileName); try { FileOutputStream fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile(); } byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); return fileName; } catch (IOException e) { e.printStackTrace(); } return null; } private static void convertHtmlToPdf(String srcFileName, String destFileName, long delayInMillsec) { try { String resizeCommand = new String("/usr/bin/wkhtmltopdf@" + srcFileName + "@--redirect-delay@" + delayInMillsec + "@" + destFileName); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); } catch (Exception e) { logger.error("something went wrong while converting pdf", e); } } public static String getFileExtenstion(String filePath) { return StringUtils.substringAfterLast(filePath, "."); } public String convertJsonToCsv(String jsonString, String targetFolderPath, String filename) { try { JSONArray docs = new JSONArray(jsonString); File file = new File(targetFolderPath + filename + DOT_CSV); String csv = CDL.toString(docs); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis() + DOT_CSV; } else { filename = filename + DOT_CSV; file = new File(targetFolderPath + filename); } FileUtils.writeStringToFile(file, csv); return filename; } catch (Exception ex) { logger.info("$ Conversion of Csv file failed ", ex); } return null; } @Override public void resourceImageUpload(String folderInBucket, String gooruBucket, String fileName, String callBackUrl, String sourceFilePath) throws Exception { Integer s3UploadFlag = 0; if (folderInBucket != null) { fileName = folderInBucket + fileName; } File file = new File(sourceFilePath + fileName); if (!file.isDirectory()) { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName, data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName, gooruBucket); s3UploadFlag = 1; } else { listFilesForFolder(file, gooruBucket, fileName); s3UploadFlag = 1; } try { if (callBackUrl != null) { final JSONObject data = new JSONObject(); final JSONObject resource = new JSONObject(); resource.put("s3UploadFlag", s3UploadFlag); data.put("resource", resource); System.out.println(callBackUrl); new ClientResource(callBackUrl).put(data.toString()); } } catch (Exception e) { e.printStackTrace(); } } public void setPublicACL(String objectKey, String gooruBucket) throws Exception { S3Object fileObject = getS3Service().getObject(gooruBucket, objectKey); AccessControlList objectAcl = getS3Service().getObjectAcl(gooruBucket, fileObject.getKey()); objectAcl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ); fileObject.setAcl(objectAcl); getS3Service().putObject(gooruBucket, fileObject); } public void listFilesForFolder(final File folder, String gooruBucket, String fileName) throws Exception { for (final File file : folder.listFiles()) { if (file.isDirectory()) { listFilesForFolder(file, gooruBucket, fileName); } else { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName + file.getName(), data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName + file.getName(), gooruBucket); } } } public RestS3Service getS3Service() { return s3Service; } @Override public void convertDocumentToPdf(Conversion conversion) { JSONObject data; try { data = new JSONObject(new JSONSerializer().serialize(conversion)); data.put("eventName", "convert.docToPdf"); try { if (conversion != null) { OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); if (conversion.getSourceFilePath() != null) { OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(new File(conversion.getSourceFilePath()), new File(conversion.getTargetFolderPath() + "/" + conversion.getFileName())); data.put("status", "completed"); convertPdfToImage(conversion.getTargetFolderPath() + "/" + conversion.getFileName(), conversion.getResourceGooruOid(), conversion.getAuthXml()); File file = new File(conversion.getSourceFilePath()); file.renameTo(new File(conversion.getTargetFolderPath() + "/" + StringUtils.substringBeforeLast(conversion.getFileName(), ".") + ".ppt")); } officeManager.stop(); } } catch (Exception e) { data.put("status", "failed"); } this.getKafkaProducer().send(data.toString()); } catch (JSONException jsonException) { logger.error("Failed to parse json : " + jsonException); } } public KafkaProducer getKafkaProducer() { return kafkaProducer; } }
package org.radargun.stages.cache.listeners.cluster; import org.radargun.DistStageAck; import org.radargun.StageResult; import org.radargun.config.Property; import org.radargun.config.Stage; import org.radargun.reporting.Report; import org.radargun.stages.AbstractDistStage; import org.radargun.stages.cache.generators.TimestampKeyGenerator.TimestampKey; import org.radargun.state.SlaveState; import org.radargun.stats.DefaultOperationStats; import org.radargun.stats.Statistics; import org.radargun.stats.SynchronizedStatistics; import org.radargun.traits.CacheListeners; import org.radargun.traits.InjectTrait; import org.radargun.utils.Projections; import org.radargun.utils.TimeConverter; import org.radargun.utils.Utils; import java.util.Collections; import java.util.List; import static org.radargun.traits.CacheListeners.*; /** * Run this stage if you want to compare performance with enabled/disabled cluster listenersTrait * * @author vchepeli@redhat.com * @since 2.0 */ @Stage(doc = "Benchmark operations performance where cluster listenersTrait are enabled or disabled.") public class RegisterListenersStage extends AbstractDistStage { @Property(doc = "Use sleep time to simulate some work on listener. Default is -1(do not sleep) ms.", converter = TimeConverter.class) protected long sleepTime = -1; @Property(doc = "Before stress stage, cluster listeners would be enabled. This is flag to turn them on. Default is false.") protected boolean registerListeners = false; @Property(doc = "Before stress stage, cluster listeners would be disabled. This is flag to turn them off. Default is false.") protected boolean unregisterListeners = false; @Property(doc = "Name of the test as used for reporting. Default is 'Test'.") protected String testName = "Listeners"; @Property(doc = "Setup if cache listener is synchronous/asynchronous. Default is true") private boolean sync = true; @Property(doc = "Allows to reset statistics at the begining of the stage. Default is false.") private boolean resetStats = false; @InjectTrait // with infinispan70 plugin private CacheListeners listenersTrait; private SynchronizedStatistics statistics; @Override public DistStageAck executeOnSlave() { String statsKey = getClass().getName() + ".Stats"; statistics = (SynchronizedStatistics) slaveState.get(statsKey); if (statistics == null) { statistics = new SynchronizedStatistics(new DefaultOperationStats()); slaveState.put(statsKey, statistics); } else if (resetStats) { statistics.reset(); } if (registerListeners) { initListenersOnSlave(slaveState); registerListeners(); } if (unregisterListeners) { unregisterListeners(); } return new ListenersAck(slaveState, statistics.snapshot(true)); } @Override public StageResult processAckOnMaster(List<DistStageAck> acks) { StageResult result = super.processAckOnMaster(acks); if (result.isError()) return result; Report.Test test = createTest(testName, null); if (test != null) { int testIteration = test.getIterations().size(); for (ListenersAck ack : Projections.instancesOf(acks, ListenersAck.class)) { if (ack.stats != null) test.addStatistics(testIteration, ack.getSlaveIndex(), Collections.singletonList(ack.stats)); } } return StageResult.SUCCESS; } protected Report.Test createTest(String testName, String iterationName) { if (testName == null || testName.isEmpty()) { log.warn("No test name - results are not recorded"); return null; } else { Report report = masterState.getReport(); return report.createTest(testName, iterationName, true); } } private void initListenersOnSlave(SlaveState slaveState) { CreatedListener createdListener = new CreatedListener() { @Override public void created(Object key, Object value) { if (sleepTime > 0) Utils.sleep(sleepTime); statistics.registerRequest(getResponseTime(key), CREATED); log.trace("Created " + key + " -> " + value); } }; slaveState.put(CREATED.name, createdListener); EvictedListener evictedListener = new EvictedListener() { @Override public void evicted(Object key, Object value) { if (sleepTime > 0) Utils.sleep(sleepTime); statistics.registerRequest(getResponseTime(key), EVICTED); log.trace("Evicted " + key + " -> " + value); } }; slaveState.put(EVICTED.name, evictedListener); RemovedListener removedListener = new RemovedListener() { @Override public void removed(Object key, Object value) { if (sleepTime > 0) Utils.sleep(sleepTime); statistics.registerRequest(getResponseTime(key), REMOVED); log.trace("Removed " + key + " -> " + value); } }; slaveState.put(REMOVED.name, removedListener); UpdatedListener updatedListener = new UpdatedListener() { @Override public void updated(Object key, Object value) { if (sleepTime > 0) Utils.sleep(sleepTime); statistics.registerRequest(getResponseTime(key), UPDATED); log.trace("Updated " + key + " -> " + value); } }; slaveState.put(UPDATED.name, updatedListener); ExpiredListener expiredListener = new ExpiredListener() { @Override public void expired(Object key, Object value) { if (sleepTime > 0) Utils.sleep(sleepTime); statistics.registerRequest(getResponseTime(key), EXPIRED); log.trace("Expired " + key + " -> " + value); } }; slaveState.put(EXPIRED.name, expiredListener); } private long getResponseTime(Object key) { if(key instanceof TimestampKey) { return (System.currentTimeMillis() - ((TimestampKey)key).getTimestamp()); } return 0; //latency of event arrival is not measured } public void registerListeners() { CreatedListener createdListener = (CreatedListener) slaveState.get(CREATED.name); if (createdListener != null && isSupported(Type.CREATED)) { listenersTrait.addCreatedListener(null, createdListener, sync); } EvictedListener evictedListener = (EvictedListener) slaveState.get(EVICTED.name); if (evictedListener != null && isSupported(Type.EVICTED)) { listenersTrait.addEvictedListener(null, evictedListener, sync); } RemovedListener removedListener = (RemovedListener) slaveState.get(REMOVED.name); if (removedListener != null && isSupported(Type.REMOVED)) { listenersTrait.addRemovedListener(null, removedListener, sync); } UpdatedListener updatedListener = (UpdatedListener) slaveState.get(UPDATED.name); if (updatedListener != null && isSupported(Type.UPDATED)) { listenersTrait.addUpdatedListener(null, updatedListener, sync); } ExpiredListener expiredListener = (ExpiredListener) slaveState.get(EXPIRED.name); if (expiredListener != null && isSupported(Type.EXPIRED)) { listenersTrait.addExpiredListener(null, expiredListener, sync); } } public void unregisterListeners() { CreatedListener createdListener = (CreatedListener) slaveState.get(CREATED.name); if (createdListener != null && isSupported(Type.CREATED)) { listenersTrait.removeCreatedListener(null, createdListener, sync); } EvictedListener evictedListener = (EvictedListener) slaveState.get(EVICTED.name); if (evictedListener != null && isSupported(Type.EVICTED)) { listenersTrait.removeEvictedListener(null, evictedListener, sync); } RemovedListener removedListener = (RemovedListener) slaveState.get(REMOVED.name); if (removedListener != null && isSupported(Type.REMOVED)) { listenersTrait.removeRemovedListener(null, removedListener, sync); } UpdatedListener updatedListener = (UpdatedListener) slaveState.get(UPDATED.name); if (updatedListener != null && isSupported(Type.UPDATED)) { listenersTrait.removeUpdatedListener(null, updatedListener, sync); } ExpiredListener expiredListener = (ExpiredListener) slaveState.get(EXPIRED.name); if (expiredListener != null && isSupported(Type.EXPIRED)) { listenersTrait.removeExpiredListener(null, expiredListener, sync); } } private boolean isSupported(Type type) { if (listenersTrait == null) { throw new IllegalArgumentException("Service does not support cache listeners"); } return listenersTrait.getSupportedListeners().contains(type); } private static class ListenersAck extends DistStageAck { public final Statistics stats; public ListenersAck(SlaveState slaveState, Statistics stats) { super(slaveState); this.stats = stats; } } }
package org.axonframework.eventstore.jdbc.criteria; import org.junit.*; import java.util.List; import static org.junit.Assert.*; /** * @author Allard Buijze */ public class JdbcCriteriaBuilderTest { @Test public void testParameterTypeRetained() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria)builder.property("property").lessThan(1.0d) .and(builder.property("property2").is(1L)) .or(builder.property("property3").isNot(1)) .or(builder.property("property4").is("1")); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); List<Object> params = parameters.getParameters(); assertTrue(params.get(0) instanceof Double); final Object param1 = params.get(1); assertTrue(param1 instanceof Long); assertTrue(params.get(2) instanceof Integer); assertTrue(params.get(3) instanceof String); } @Test public void testBuildCriteria_ComplexStructureWithUnequalNull() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThan("less") .and(builder.property("property2").greaterThan("gt")) .or(builder.property("property3").notIn(builder.property("collection"))) .or(builder.property("property4").isNot(null)); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property < ?) AND (entry.property2 > ?)) OR (entry.property3 NOT IN entry.collection)) OR (entry.property4 IS NOT NULL)", query.toString()); assertEquals(2, parameters.getParameters().size()); assertEquals("less", parameters.getParameters().get(0)); assertEquals("gt", parameters.getParameters().get(1)); } @Test public void testBuildCriteria_ComplexStructureWithUnequalValue() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThan("less") .and(builder.property("property2").greaterThanEquals("gte")) .or(builder.property("property3").in(new String[]{"piet", "klaas"})) .or(builder.property("property4").isNot("4")); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property < ?) AND (entry.property2 >= ?)) OR (entry.property3 IN (?,?))) OR (entry.property4 <> ?)", query.toString()); assertEquals(5, parameters.getParameters().size()); assertEquals("less", parameters.getParameters().get(0)); assertEquals("gte", parameters.getParameters().get(1)); assertEquals("4", parameters.getParameters().get(4)); assertEquals("piet", parameters.getParameters().get(2)); assertEquals("klaas", parameters.getParameters().get(3)); } @Test public void testBuildCriteria_ComplexStructureWithUnequalProperty() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThanEquals("lte") .and(builder.property("property2").greaterThanEquals("gte")) .or(builder.property("property3").in(new String[]{"piet", "klaas"})) .or(builder.property("property4").isNot(builder.property("property4"))); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property <= ?) AND (entry.property2 >= ?)) OR (entry.property3 IN (?,?))) OR (entry.property4 <> entry.property4)", query.toString()); assertEquals(4, parameters.getParameters().size()); assertEquals("lte", parameters.getParameters().get(0)); assertEquals("gte", parameters.getParameters().get(1)); assertEquals("piet", parameters.getParameters().get(2)); assertEquals("klaas", parameters.getParameters().get(3)); } @Test public void testBuildCriteria_ComplexStructureWithEqualNull() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThan("less") .and(builder.property("property2").greaterThanEquals("gte")) .or(builder.property("property3").in(new String[]{"piet", "klaas"})) .or(builder.property("property4").is(null)); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property < ?) AND (entry.property2 >= ?)) OR (entry.property3 IN (?,?))) OR (entry.property4 IS NULL)", query.toString()); assertEquals(4, parameters.getParameters().size()); assertEquals("less", parameters.getParameters().get(0)); assertEquals("gte", parameters.getParameters().get(1)); assertEquals("piet", parameters.getParameters().get(2)); assertEquals("klaas", parameters.getParameters().get(3)); } @Test public void testBuildCriteria_ComplexStructureWithEqualValue() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThan("less") .and(builder.property("property2").greaterThanEquals("gte")) .or(builder.property("property3").in(new String[]{"piet", "klaas"})) .or(builder.property("property4").is("4")); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property < ?) AND (entry.property2 >= ?)) OR (entry.property3 IN (?,?))) OR (entry.property4 = ?)", query.toString()); assertEquals(5, parameters.getParameters().size()); assertEquals("less", parameters.getParameters().get(0)); assertEquals("gte", parameters.getParameters().get(1)); assertEquals("4", parameters.getParameters().get(4)); assertEquals("piet", parameters.getParameters().get(2)); assertEquals("klaas", parameters.getParameters().get(3)); } @Test public void testBuildCriteria_ComplexStructureWithEqualProperty() throws Exception { JdbcCriteriaBuilder builder = new JdbcCriteriaBuilder(); JdbcCriteria criteria = (JdbcCriteria) builder.property("property").lessThan(builder.property("prop1")) .and(builder.property("property2").greaterThanEquals("gte")) .or(builder.property("property3").in(new String[]{"piet", "klaas"})) .or(builder.property("property4").is(builder.property("property4"))); StringBuilder query = new StringBuilder(); ParameterRegistry parameters = new ParameterRegistry(); criteria.parse("entry", query, parameters); assertEquals( "(((entry.property < entry.prop1) AND (entry.property2 >= ?)) OR (entry.property3 IN (?,?))) OR (entry.property4 = entry.property4)", query.toString()); assertEquals(3, parameters.getParameters().size()); assertEquals("gte", parameters.getParameters().get(0)); assertEquals("piet", parameters.getParameters().get(1)); assertEquals("klaas", parameters.getParameters().get(2)); }}
package io.jenkins.plugins.dexter; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Scanner; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.*; import net.sf.json.JSONObject; public class DexterPublisher extends Recorder { private boolean createServer; private String pathDexter; private String projectFullPath; private String sourceDir; private String binDir; private String headerDir; private final String analyseFileName; private final boolean file; private final boolean folder; private final boolean project; private final boolean snapshot; private String dexterServer; private String dexterPort; private String dexterUser; private String dexterPassword; private String pathToBat = ""; private String serverDisc = ""; private String dexterDisc = ""; private String dexterServerPath = ""; private String pathConfig = ""; private String projectName = ""; private String projectType = ""; String message; public String getPathConfig() { return pathConfig; } // Fields in config.jelly must match the parameter names in the // "DataBoundConstructor" @DataBoundConstructor public DexterPublisher(boolean createServer, String dexterServerPath, String dexterServer, String dexterPort, String dexterUser, String dexterPassword, String pathDexter, String projectFullPath, String sourceDir, String binDir, String headerDir, String analyseFileName, boolean file, boolean folder, boolean project, boolean snapshot) { this.createServer = createServer; this.dexterServerPath = dexterServerPath; this.dexterServer = dexterServer; this.dexterPort = dexterPort; this.dexterUser = dexterUser; this.dexterPassword = dexterPassword; this.pathDexter = pathDexter; this.projectFullPath = projectFullPath; this.sourceDir = sourceDir; this.binDir = binDir; this.headerDir = headerDir; this.analyseFileName = analyseFileName; this.file = file; this.folder = folder; this.project = project; this.snapshot = snapshot; } public boolean isCreateServer() { return createServer; } public void setCreateServer(boolean createServer) { this.createServer = createServer; } public String getAnalyseFileName() { return analyseFileName; } public String getHeaderDir() { return headerDir; } public static String getFilename() { return filename; } public String getProjectName() { return "project"; } public String getProjectFullPath() { return projectFullPath; } public String getSourceDir() { return sourceDir; } public String getBinDir() { return binDir; } public boolean isFile() { return file; } public boolean isFolder() { return folder; } public boolean isProject() { return project; } public boolean isSnapshot() { return snapshot; } public String getName() { return pathDexter; } public String getDexterServer() { return dexterServer; } public String getDexterPort() { return dexterPort; } public void setDexterPort(String dexterPort) { this.dexterPort = dexterPort; } public String getDexterUser() { return dexterUser; } public void setDexterUser(String dexterUser) { this.dexterUser = dexterUser; } public String getDexterPassword() { return dexterPassword; } public void setDexterPassword(String dexterPassword) { this.dexterPassword = dexterPassword; } public void setDexterServer(String dexterServer) { this.dexterServer = dexterServer; } private static String OS = null; public static String getOsName() { if (OS == null) { OS = System.getProperty("os.name"); } return OS; } public static boolean isWindows() { return getOsName().startsWith("Windows"); } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { pathToBat = pathDexter + "/bin"; pathConfig = pathDexter + "/bin/dexter_cfg.json"; projectName = getProjectName(); serverDisc = dexterServerPath.substring(0, 2); dexterDisc = pathDexter.substring(0, 2); if (file) { projectType = "FILE"; } if (folder) { projectType = "FOLDER"; } if (project) { projectType = "PROJECT"; } if (snapshot) { projectType = "SNAPSHOT"; } if (isCreateServer()) { if (isWindows()) { writeToBatFile(); Runtime runtime = Runtime.getRuntime(); String command = "cmd /c start /wait cmd.exe /K " + "\"cd " + dexterServerPath + " && " + serverDisc + " && run.bat \""; try { runtime.exec(command); } catch (IOException e) { e.printStackTrace(); } writeToFile(); String commandDexter = "cmd /c start cmd.exe /K " + "\"cd " + pathToBat + " && " + dexterDisc + " && dexter.bat " + dexterUser + " " + dexterPassword + " > logs.txt \""; try { runtime.exec(commandDexter); } catch (IOException e) { e.printStackTrace(); } if (readFile(pathToBat + "//logs.txt")) { message = stringBufferOfData.toString(); } else message = "Error saving logs"; } else { writeToShFile(); writeToFile(); try { int ch; ProcessBuilder pb = new ProcessBuilder(dexterServerPath + "/run.sh"); pb.directory(new File(dexterServerPath)); Process shellProcess = pb.start(); ProcessBuilder pbClient = new ProcessBuilder(pathToBat + "/dexter.sh", dexterUser, dexterPassword); pbClient.directory(new File(pathToBat)); Process shellProcessClient = pbClient.start(); InputStreamReader myIStreamReader = new InputStreamReader(shellProcessClient.getInputStream()); while ((ch = myIStreamReader.read()) != -1) { System.out.print((char) ch); char temp = (char) ch; message = message + Character.toString(temp); shellProcess.destroy(); } } catch (IOException anIOException) { System.out.println(anIOException); } catch (Exception e) { e.printStackTrace(); } } } DexterBuildAction buildAction = new DexterBuildAction(message, build); build.addAction(buildAction); return true; } static StringBuffer stringBufferOfData = new StringBuffer(); static String filename = null; static Scanner sc = new Scanner(System.in, "UTF-8"); private boolean readFile(String filenameRead) { filename = filenameRead; Scanner fileToRead = null; try { stringBufferOfData.replace(0, stringBufferOfData.length(), " "); fileToRead = new Scanner(new File(filename), "UTF-8"); for (String line; fileToRead.hasNextLine() && (line = fileToRead.nextLine()) != null;) { System.out.println(line); stringBufferOfData.append(line).append("\n"); } fileToRead.close(); return true; } catch (FileNotFoundException ex) { System.out.println("The file " + filename + " could not be found! " + ex.getMessage()); return false; } finally { if (fileToRead != null) { fileToRead.close(); } return true; } } private void writeToBatFile() { OpenOption myOpt = StandardOpenOption.CREATE; try { Path fileToWrite = Paths.get(dexterServerPath + "/run.bat"); BufferedWriter bufwriter = Files.newBufferedWriter(fileToWrite, Charset.forName("UTF-8"), myOpt); bufwriter.write("node server.js -database.host="); bufwriter.write(dexterServer); bufwriter.write(" -p="); bufwriter.write(dexterPort); bufwriter.write(" -database.name=my_dexter_db -database.user="); bufwriter.write(dexterUser); bufwriter.write(" -database.password="); bufwriter.write(dexterPassword); bufwriter.close(); } catch (Exception e) { System.out.println("Error occured while attempting to write to file: " + e.getMessage()); } } private void writeToShFile() { OpenOption myOpt = StandardOpenOption.CREATE; try { Path fileToWrite = Paths.get(dexterServerPath + "/run.sh"); BufferedWriter bufwriter = Files.newBufferedWriter(fileToWrite, Charset.forName("UTF-8"), myOpt); bufwriter.write("node server.js -database.host="); bufwriter.write(dexterServer); bufwriter.write(" -p="); bufwriter.write(dexterPort); bufwriter.write(" -database.name=my_dexter_db -database.user="); bufwriter.write(dexterUser); bufwriter.write(" -database.password="); bufwriter.write(dexterPassword); bufwriter.close(); } catch (Exception e) { System.out.println("Error occured while attempting to write to file: " + e.getMessage()); } } private void writeToFile() { OpenOption myOpt = StandardOpenOption.CREATE; try { Path fileToWrite = Paths.get(pathConfig); BufferedWriter bufwriter = Files.newBufferedWriter(fileToWrite, Charset.forName("UTF-8"), myOpt); bufwriter.write("{\n"); bufwriter.write("\"dexterHome\":\"" + pathDexter + "\", \n"); bufwriter.write("\"dexterServerIp\":\"" + dexterServer + "\", \n"); bufwriter.write("\"dexterServerPort\":\"" + dexterPort + "\", \n"); bufwriter.write("\"projectName\":\"" + projectName + "\", \n"); bufwriter.write("\"projectFullPath\":\"" + projectFullPath + "\", \n"); bufwriter.write("\"sourceDir\":[\"" + sourceDir + "\"], \n"); bufwriter.write("\"headerDir\":[\"" + headerDir + "\"], \n"); bufwriter.write("\"sourceEncoding\":\"UTF-8\", \n"); bufwriter.write("\"libDir\":[], \n"); bufwriter.write("\"binDir\":\"\", \n"); bufwriter.write("\"modulePath\":\"\", \n"); bufwriter.write("\"fileName\":[\"" + analyseFileName + "\"], \n"); bufwriter.write("\"type\":\"" + projectType + "\" \n"); bufwriter.write("}\n"); bufwriter.close(); } catch (Exception e) { System.out.println("Error occured while attempting to write to file: " + e.getMessage()); } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new DexterProjectAction(project); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { load(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } public String getDisplayName() { return "Dexter Static Analysis"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { save(); return super.configure(req, formData); } } }
package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import static org.elasticsearch.watcher.support.Exceptions.illegalState; public class WatchStore extends AbstractComponent { public static final String INDEX = ".watches"; public static final String DOC_TYPE = "watch"; private final ClientProxy client; private final Watch.Parser watchParser; private final ConcurrentMap<String, Watch> watches; private final AtomicBoolean started = new AtomicBoolean(false); private final int scrollSize; private final TimeValue scrollTimeout; @Inject public WatchStore(Settings settings, ClientProxy client, Watch.Parser watchParser) { super(settings); this.client = client; this.watchParser = watchParser; this.watches = ConcurrentCollections.newConcurrentMap(); this.scrollTimeout = settings.getAsTime("watcher.watch.scroll.timeout", TimeValue.timeValueSeconds(30)); this.scrollSize = settings.getAsInt("watcher.watch.scroll.size", 100); } public void start(ClusterState state) throws Exception { if (started.get()) { logger.debug("watch store already started"); return; } IndexMetaData watchesIndexMetaData = state.getMetaData().index(INDEX); if (watchesIndexMetaData != null) { try { int count = loadWatches(watchesIndexMetaData.getNumberOfShards()); logger.debug("loaded [{}] watches from the watches index [{}]", count, INDEX); started.set(true); } catch (Exception e) { logger.debug("failed to load watches for watch index [{}]", e, INDEX); watches.clear(); throw e; } } else { started.set(true); } } public boolean validate(ClusterState state) { IndexMetaData watchesIndexMetaData = state.getMetaData().index(INDEX); if (watchesIndexMetaData == null) { logger.debug("index [{}] doesn't exist, so we can start", INDEX); return true; } if (state.routingTable().index(INDEX).allPrimaryShardsActive()) { logger.debug("index [{}] exists and all primary shards are started, so we can start", INDEX); return true; } else { logger.debug("not all primary shards active for index [{}], so we cannot start", INDEX); return false; } } public boolean started() { return started.get(); } public void stop() { if (started.compareAndSet(true, false)) { watches.clear(); logger.info("stopped watch store"); } } /** * Returns the watch with the specified id otherwise <code>null</code> is returned. */ public Watch get(String id) { ensureStarted(); return watches.get(id); } /** * Creates an watch if this watch already exists it will be overwritten */ public WatchPut put(Watch watch) throws IOException { ensureStarted(); IndexRequest indexRequest = createIndexRequest(watch.id(), watch.getAsBytes(), Versions.MATCH_ANY); IndexResponse response = client.index(indexRequest, (TimeValue) null); watch.status().version(response.getVersion()); watch.version(response.getVersion()); Watch previous = watches.put(watch.id(), watch); return new WatchPut(previous, watch, response); } /** * Updates and persists the status of the given watch */ public void updateStatus(Watch watch) throws IOException { ensureStarted(); if (!watch.status().dirty()) { return; } // at the moment we store the status together with the watch, // so we just need to update the watch itself // TODO: consider storing the status in a different documment (watch_status doc) (must smaller docs... faster for frequent updates) XContentBuilder source = JsonXContent.contentBuilder(). startObject() .field(Watch.Field.STATUS.getPreferredName(), watch.status(), ToXContent.EMPTY_PARAMS) .endObject(); UpdateRequest updateRequest = new UpdateRequest(INDEX, DOC_TYPE, watch.id()); updateRequest.doc(source); updateRequest.version(watch.version()); UpdateResponse response = client.update(updateRequest); watch.status().version(response.getVersion()); watch.version(response.getVersion()); watch.status().resetDirty(); // Don't need to update the watches, since we are working on an instance from it. } /** * Deletes the watch with the specified id if exists */ public WatchDelete delete(String id, boolean force) { ensureStarted(); Watch watch = watches.remove(id); // even if the watch was not found in the watch map, we should still try to delete it // from the index, just to make sure we don't leave traces of it DeleteRequest request = new DeleteRequest(INDEX, DOC_TYPE, id); if (watch != null && !force) { request.version(watch.version()); } DeleteResponse response = client.delete(request); // Another operation may hold the Watch instance, so lets set the version for consistency: if (watch != null) { watch.version(response.getVersion()); } return new WatchDelete(response); } public Collection<Watch> watches() { return watches.values(); } public Collection<Watch> activeWatches() { Set<Watch> watches = new HashSet<>(); for (Watch watch : watches()) { if (watch.status().state().isActive()) { watches.add(watch); } } return watches; } public int watchCount() { return watches.size(); } IndexRequest createIndexRequest(String id, BytesReference source, long version) { IndexRequest indexRequest = new IndexRequest(INDEX, DOC_TYPE, id); indexRequest.source(source.toBytes()); indexRequest.version(version); return indexRequest; } /** * scrolls all the watch documents in the watches index, parses them, and loads them into * the given map. */ int loadWatches(int numPrimaryShards) { assert watches.isEmpty() : "no watches should reside, but there are [" + watches.size() + "] watches."; RefreshResponse refreshResponse = client.refresh(new RefreshRequest(INDEX)); if (refreshResponse.getSuccessfulShards() < numPrimaryShards) { throw illegalState("not all required shards have been refreshed"); } int count = 0; SearchRequest searchRequest = new SearchRequest(INDEX) .types(DOC_TYPE) .preference("_primary") .scroll(scrollTimeout) .source(new SearchSourceBuilder() .size(scrollSize) .sort(SortBuilders.fieldSort("_doc")) .version(true)); SearchResponse response = client.search(searchRequest, null); try { if (response.getTotalShards() != response.getSuccessfulShards()) { throw new ElasticsearchException("Partial response while loading watches"); } while (response.getHits().hits().length != 0) { for (SearchHit hit : response.getHits()) { String id = hit.getId(); try { Watch watch = watchParser.parse(id, true, hit.getSourceRef()); watch.status().version(hit.version()); watch.version(hit.version()); watches.put(id, watch); count++; } catch (Exception e) { logger.error("couldn't load watch [{}], ignoring it...", e, id); } } response = client.searchScroll(response.getScrollId(), scrollTimeout); } } finally { client.clearScroll(response.getScrollId()); } return count; } private void ensureStarted() { if (!started.get()) { throw new IllegalStateException("watch store not started"); } } public class WatchPut { private final Watch previous; private final Watch current; private final IndexResponse response; public WatchPut(Watch previous, Watch current, IndexResponse response) { this.current = current; this.previous = previous; this.response = response; } public Watch current() { return current; } public Watch previous() { return previous; } public IndexResponse indexResponse() { return response; } } public class WatchDelete { private final DeleteResponse response; public WatchDelete(DeleteResponse response) { this.response = response; } public DeleteResponse deleteResponse() { return response; } } }
package org.eclipse.birt.report.engine.util; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.util.logging.Logger; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; public class SvgFile { private static Logger logger = Logger.getLogger( SvgFile.class.getName( ) ); static boolean isSvg = false; public static boolean isSvg( String uri ) { if ( uri != null && uri.endsWith( ".svg" ) ) { isSvg = true; } else { isSvg = false; } return isSvg; } public static boolean isSvg( String mimeType, String uri, String extension ) { isSvg = ( ( mimeType != null ) && mimeType .equalsIgnoreCase( "image/svg+xml" ) ) //$NON-NLS-1$ || ( ( uri != null ) && uri.toLowerCase( ).endsWith( ".svg" ) ) //$NON-NLS-1$ || ( ( extension != null ) && extension.toLowerCase( ) .endsWith( ".svg" ) ); //$NON-NLS-1$ return isSvg; } public static byte[] transSvgToArray( String uri ) throws Exception { InputStream in = new URL( uri ).openStream( ); try { return transSvgToArray( in ); } finally { in.close( ); } } public static byte[] transSvgToArray( InputStream inputStream ) throws Exception { PNGTranscoder transcoder = new PNGTranscoder( ); // create the transcoder input TranscoderInput input = new TranscoderInput( inputStream ); // create the transcoder output ByteArrayOutputStream ostream = new ByteArrayOutputStream( ); TranscoderOutput output = new TranscoderOutput( ostream ); transcoder.transcode( input, output ); // flush the stream ostream.flush( ); // use the output stream as Image input stream. return ostream.toByteArray( ); } }
package com.example.flutter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.chromium.base.PathUtils; import org.domokit.activity.ActivityImpl; import io.flutter.view.FlutterMain; import io.flutter.view.FlutterView; import java.io.File; import org.json.JSONException; import org.json.JSONObject; public class ExampleActivity extends Activity { private static final String TAG = "ExampleActivity"; private FlutterView flutterView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FlutterMain.ensureInitializationComplete(getApplicationContext(), null); setContentView(R.layout.hello_services_layout); flutterView = (FlutterView) findViewById(R.id.flutter_view); File appBundle = new File(PathUtils.getDataDirectory(this), FlutterMain.APP_BUNDLE); flutterView.runFromBundle(appBundle.getPath(), null); flutterView.addOnMessageListener("getLocation", new FlutterView.OnMessageListener() { @Override public String onMessage(String message) { return onGetLocation(message); } }); Button getRandom = (Button) findViewById(R.id.get_random); getRandom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendGetRandom(); } }); } @Override protected void onDestroy() { if (flutterView != null) { flutterView.destroy(); } super.onDestroy(); } @Override protected void onPause() { super.onPause(); flutterView.onPause(); } @Override protected void onPostResume() { super.onPostResume(); flutterView.onPostResume(); } @Override protected void onNewIntent(Intent intent) { // Reload the Flutter Dart code when the activity receives an intent // from the "flutter refresh" command. // This feature should only be enabled during development. Use the // debuggable flag as an indicator that we are in development mode. if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { if (Intent.ACTION_RUN.equals(intent.getAction())) { flutterView.runFromBundle(intent.getDataString(), intent.getStringExtra("snapshot")); } } } private void sendGetRandom() { JSONObject message = new JSONObject(); try { message.put("min", 1); message.put("max", 1000); } catch (JSONException e) { Log.e(TAG, "JSON exception", e); return; } flutterView.sendToFlutter("getRandom", message.toString(), new FlutterView.MessageReplyCallback() { @Override public void onReply(String json) { onRandomReply(json); } }); } private void onRandomReply(String json) { double value; try { JSONObject reply = new JSONObject(json); value = reply.getDouble("value"); } catch (JSONException e) { Log.e(TAG, "JSON exception", e); return; } TextView randomValue = (TextView) findViewById(R.id.random_value); randomValue.setText(Double.toString(value)); } private String onGetLocation(String json) { String provider; try { JSONObject message = new JSONObject(json); provider = message.getString("provider"); } catch (JSONException e) { Log.e(TAG, "JSON exception", e); return null; } String locationProvider; if (provider.equals("network")) { locationProvider = LocationManager.NETWORK_PROVIDER; } else if (provider.equals("gps")) { locationProvider = LocationManager.GPS_PROVIDER; } else { return null; } LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(locationProvider); JSONObject reply = new JSONObject(); try { if (location != null) { reply.put("latitude", location.getLatitude()); reply.put("longitude", location.getLongitude()); } else { reply.put("latitude", 0); reply.put("longitude", 0); } } catch (JSONException e) { Log.e(TAG, "JSON exception", e); return null; } return reply.toString(); } }
package com.plugin.gcm; import android.app.NotificationManager; import com.google.android.gcm.GCMRegistrar; import com.appgyver.event.EventService; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Notification Service - Handles Push Notification and deliver the messages to all web views * that have registered callbacks. */ public class NotificationService { public static final String USER_ACTION = "userAction"; private static String TAG = "PushPlugin-NotificationService"; public static final String REG_ID = "regID"; public static final String FOREGROUND = "foreground"; public static final String COLDSTART = "coldstart"; public static final String FROM = "from"; public static final String COLLAPSE_KEY = "collapse_key"; public static final String MESSAGE = "message"; public static final String MSGCNT = "msgcnt"; public static final String SOUNDNAME = "soundname"; public static final String JSON_START_PREFIX = "{"; public static final String JSON_ARRAY_START_PREFIX = "["; public static final String PAYLOAD = "payload"; private static NotificationService sInstance; private boolean mIsActive = false; private final Context mContext; private String mSenderID; private List<WebViewReference> mWebViewReferences = new ArrayList<WebViewReference>(); private String mRegistrationID = null; private List<JSONObject> mNotifications = new ArrayList<JSONObject>(); private boolean mForeground = false; public NotificationService(Context context) { mContext = context; EventService.getInstance().addEventListener(EventService.STEROIDS_APPLICATION_STARTED, new EventService.EventHandler() { @Override public void call(Object eventContext) { mIsActive = true; } }); EventService.getInstance().addEventListener(EventService.STEROIDS_APPLICATION_ENDED, new EventService.EventHandler() { @Override public void call(Object eventContext) { cleanUp(); mIsActive = false; } }); } public boolean isActive() { return mIsActive; } public static NotificationService getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationService(context); } return sInstance; } public void setSenderID(String senderID) { if (senderID != null && senderID.trim().length() > 0) { mSenderID = senderID; } } public void addRegisterCallBack(CordovaWebView webView, CallbackContext callBack) { WebViewReference webViewReference = getWebViewReference(webView); webViewReference.setRegisterCallBack(callBack); if (isRegistered()) { webViewReference.notifyRegistered(); } else { registerDevice(); } } public void addNotificationForegroundCallBack(CordovaWebView webView, CallbackContext callBack) { WebViewReference webViewReference = getWebViewReference(webView); webViewReference.setNotificationForegroundCallBack(callBack); flushNotificationToWebView(webViewReference); } public void addNotificationBackgroundCallBack(CordovaWebView webView, CallbackContext callBack) { WebViewReference webViewReference = getWebViewReference(webView); webViewReference.setNotificationBackgroundCallBack(callBack); flushNotificationToWebView(webViewReference); } public void removeWebView(CordovaWebView webView) { WebViewReference webViewReference = findWebViewReference(webView); if (webViewReference != null) { mWebViewReferences.remove(webViewReference); webViewReference.destroy(); Log.v(TAG, "removeWebView : " + webView + " - after remove -> mWebViewReferences: " + mWebViewReferences); } } private WebViewReference findWebViewReference(CordovaWebView webView) { WebViewReference webViewReference = null; for (WebViewReference item : mWebViewReferences) { if (item.getWebView() == webView) { webViewReference = item; break; } } return webViewReference; } private WebViewReference getWebViewReference(CordovaWebView webView) { WebViewReference webViewReference = findWebViewReference(webView); if (webViewReference == null) { webViewReference = createWebViewReference(webView); } return webViewReference; } public void registerWebView(CordovaWebView webView) { getWebViewReference(webView); } private boolean isRegistered() { return mRegistrationID != null; } private WebViewReference createWebViewReference(CordovaWebView webView) { WebViewReference webViewReference = new WebViewReference(this, webView); mWebViewReferences.add(webViewReference); return webViewReference; } private void registerDevice() { if (mSenderID == null) { throw new IllegalArgumentException( "sender ID is required in order to register this device for push notifications. You must specify the senderId in the ApplicationManifest or when calling the JavaScript API."); } GCMRegistrar.register(mContext, mSenderID); } public void onRegistered(String regId) { mRegistrationID = regId; notifyRegisteredToAllWebViews(); } private void notifyRegisteredToAllWebViews() { for (WebViewReference webViewReference : mWebViewReferences) { webViewReference.notifyRegistered(); } } public void onMessage(Bundle extras) { onMessage(extras, false); } /** * Deliver a notification message.. * @param extras * @param userAction - When this flag is true we try to remove a duplicate notification. * This only happens when the IntentService delivers the notification * and the PushHandlerActivity also delivers the same notification * because the user tapped in the notification. * */ public void onMessage(Bundle extras, boolean userAction) { JSONObject notification = createNotificationJSON(extras); if(userAction) { tryToRemoveDuplicate(notification); try { notification.put(USER_ACTION, true); } catch (JSONException e) { /*no op*/ } } Log.v(TAG, "onMessage() -> isForeground: " + isForeground() + " notification: " + notification); addNotification(notification); notifyAllWebViews(); } private void tryToRemoveDuplicate(JSONObject notification) { int idx = 0; boolean found = false; for(idx = 0; idx < mNotifications.size(); idx++){ JSONObject item = mNotifications.get(idx); if(isEqual(notification, item)){ found = true; break; } } if(found){ Log.v(TAG, "tryToRemoveDuplicate() Duplicate found.. and removed."); mNotifications.remove(idx); } } private boolean isEqual(JSONObject from, JSONObject to) { boolean isEqual = false; if(from != null && to != null && from.length() == to.length()){ try { Iterator<String> keys = from.keys(); isEqual = true; while (keys.hasNext() && isEqual) { String key = keys.next(); if(from.get(key) == null && to.get(key) == null){ continue; } if(from.get(key) instanceof JSONObject){ isEqual = isEqual((JSONObject)from.get(key), (JSONObject)to.get(key)); } else{ isEqual = from.get(key).equals(to.get(key)); } } } catch(Exception exp){ /*no op*/ } } else{ isEqual = false; } return isEqual; } private void notifyAllWebViews() { for (WebViewReference webViewReference : mWebViewReferences) { flushNotificationToWebView(webViewReference); } } private void flushNotificationToWebView(WebViewReference webViewReference) { Log.v(TAG, "flushNotificationToWebView() - Notifications.size(): " + mNotifications.size() + " -> webViewReference: " + webViewReference); for (JSONObject notification : mNotifications) { webViewReference.sendNotification(notification); } } private void addNotification(JSONObject notification) { mNotifications.add(notification); } private JSONObject createNotificationJSON(Bundle extras) { try { JSONObject notification = new JSONObject(); JSONObject payload = new JSONObject(); Iterator<String> it = extras.keySet().iterator(); while (it.hasNext()) { String key = it.next(); if (parseSystemData(key, notification, extras)) { continue; } parseLegacyProperty(key, notification, extras); parseJsonProperty(key, notification, extras, payload); } notification.put(PAYLOAD, payload); notification.put(FOREGROUND, isForeground()); return notification; } catch (JSONException e) { Log.e(TAG, "extrasToJSON: JSON exception"); } return null; } // Try to figure out if the value is another JSON object or JSON Array private void parseJsonProperty(String key, JSONObject json, Bundle extras, JSONObject jsondata) throws JSONException { if (extras.get(key) instanceof String) { String strValue = extras.getString(key); if (strValue.startsWith(JSON_START_PREFIX)) { try { JSONObject jsonObj = new JSONObject(strValue); jsondata.put(key, jsonObj); } catch (Exception e) { jsondata.put(key, strValue); } } else if (strValue.startsWith(JSON_ARRAY_START_PREFIX)) { try { JSONArray jsonArray = new JSONArray(strValue); jsondata.put(key, jsonArray); } catch (Exception e) { jsondata.put(key, strValue); } } else { if(!json.has(key)) { jsondata.put(key, strValue); } } } } // Maintain backwards compatibility private void parseLegacyProperty(String key, JSONObject json, Bundle extras) throws JSONException { if (key.equals(MESSAGE) || key.equals(MSGCNT) || key.equals(SOUNDNAME)) { json.put(key, extras.get(key)); } } private boolean parseSystemData(String key, JSONObject json, Bundle extras) throws JSONException { boolean found = false; if (key.equals(FROM) || key.equals(COLLAPSE_KEY)) { json.put(key, extras.get(key)); found = true; } else if (key.equals(COLDSTART)) { json.put(key, extras.getBoolean(COLDSTART)); found = true; } return found; } public void setForeground(boolean foreground) { if(mForeground != foreground){ Log.v(TAG, "setForeground() -> oldValue: " + mForeground + " newValue: " + foreground); if(!foreground){ final NotificationManager notificationManager = (NotificationManager) cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancelAll(); } } mForeground = foreground; } public boolean isForeground() { return mForeground; } public void onDestroy() { GCMRegistrar.onDestroy(mContext); cleanUp(); sInstance = null; } public void unRegister() { Log.v(TAG, "unRegister"); GCMRegistrar.unregister(mContext); mRegistrationID = null; cleanUp(); } private void cleanUp() { Log.v(TAG, "Cleaning up"); mWebViewReferences.clear(); mNotifications.clear(); } static class WebViewReference { private CordovaWebView mWebView; private CallbackContext mRegisterCallBack; private CallbackContext mNotificationForegroundCallBack; private CallbackContext mNotificationBackgroundCallBack; private NotificationService mNotificationService; private boolean mNotifiedOfRegistered = false; private List<JSONObject> mNotifications = new ArrayList<JSONObject>(); public WebViewReference(NotificationService notificationService, CordovaWebView webView) { mNotificationService = notificationService; mWebView = webView; } public void destroy() { mWebView = null; mRegisterCallBack = null; mNotificationForegroundCallBack = null; mNotificationBackgroundCallBack = null; mNotificationService = null; mNotifications.clear(); } public boolean hasNotifiedOfRegistered() { return mNotifiedOfRegistered; } public void setNotifiedOfRegistered(boolean notifiedOfRegistered) { mNotifiedOfRegistered = notifiedOfRegistered; } public CordovaWebView getWebView() { return mWebView; } public boolean hasNotification(JSONObject notification) { return mNotifications.contains(notification); } public void notifyRegistered() { if (hasNotifiedOfRegistered()) { Log.v(TAG, "notifyRegistered() - Webview already notified of registration. skipping callback. webview: " + getWebView()); return; } if (getRegisterCallBack() != null) { setNotifiedOfRegistered(true); getRegisterCallBack().success(mNotificationService.mRegistrationID); } else { Log.v(TAG, "No Register callback - webview: " + getWebView()); } } public void sendNotification(JSONObject notification) { if (hasNotification(notification)) { //Log.v(TAG, // "sendNotification() - Webview already received this notification. skipping callback. webview: " // + getWebView()); return; } boolean isForeground = true; try { isForeground = notification.getBoolean(FOREGROUND); } catch (JSONException e) { /*no op*/ } if (isForeground) { Log.v(TAG, "sendNotification() - foreground callback - webview: " + getWebView()); sendNotification(getNotificationForegroundCallBack(), notification); } else { Log.v(TAG, "sendNotification() - background callback - webview: " + getWebView()); sendNotification(getNotificationBackgroundCallBack(), notification); } } private void sendNotification(CallbackContext callBack, JSONObject notification) { if (callBack != null) { PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, notification); pluginResult.setKeepCallback(true); callBack.sendPluginResult(pluginResult); mNotifications.add(notification); } else { Log.v(TAG, "No Notification callback - webview: " + getWebView()); } } public void setNotificationForegroundCallBack(CallbackContext callBack) { Log.v(TAG, "setNotificationForegroundCallBack() - webview: " + getWebView()); mNotificationForegroundCallBack = callBack; } public void setNotificationBackgroundCallBack(CallbackContext callBack) { Log.v(TAG, "setNotificationBackgroundCallBack() - webview: " + getWebView()); mNotificationBackgroundCallBack = callBack; } public CallbackContext getNotificationForegroundCallBack() { return mNotificationForegroundCallBack; } public CallbackContext getNotificationBackgroundCallBack() { return mNotificationBackgroundCallBack; } public void setRegisterCallBack(CallbackContext callBack) { mRegisterCallBack = callBack; } public CallbackContext getRegisterCallBack() { return mRegisterCallBack; } @Override public String toString() { String webViewStr = "empty"; if (getWebView() != null) { webViewStr = getWebView().toString(); } return "WebViewReference -> " + webViewStr; } } }
package org.exist.xquery.modules.mail; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Version; import org.exist.dom.QName; import org.exist.util.MimeTable; import org.exist.xquery.*; import org.exist.xquery.value.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import jakarta.activation.DataHandler; import jakarta.mail.*; import jakarta.mail.internet.*; import jakarta.mail.util.ByteArrayDataSource; import javax.annotation.Nullable; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.util.*; import java.util.regex.Pattern; public class SendEmailFunction extends BasicFunction { private static final Logger LOGGER = LogManager.getLogger(SendEmailFunction.class); private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance(); private final static int MIME_BASE64_MAX_LINE_LENGTH = 76; //RFC 2045, page 24 /** * Regular expression for checking for an RFC 2045 non-token. */ private static final Pattern NON_TOKEN_PATTERN = Pattern.compile("^.*[\\s\\p{Cntrl}()<>@,;:\\\"/\\[\\]?=].*$"); static final String ERROR_MSG_NON_MIME_CLIENT = "Error your mail client is not MIME Compatible"; public final static FunctionSignature deprecated = new FunctionSignature( new QName("send-email", MailModule.NAMESPACE_URI, MailModule.PREFIX), "Sends an email through the SMTP Server.", new SequenceType[] { new FunctionParameterSequenceType("email", Type.ELEMENT, Cardinality.ONE_OR_MORE, "The email message in the following format: <mail> <from/> <reply-to/> <to/> <cc/> <bcc/> <subject/> <message> <text/> <xhtml/> </message> <attachment filename=\"\" mimetype=\"\">xs:base64Binary</attachment> </mail>."), new FunctionParameterSequenceType("server", Type.STRING, Cardinality.ZERO_OR_ONE, "The SMTP server. If empty, then it tries to use the local sendmail program."), new FunctionParameterSequenceType("charset", Type.STRING, Cardinality.ZERO_OR_ONE, "The charset value used in the \"Content-Type\" message header (Defaults to UTF-8)") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.ONE_OR_MORE, "true if the email message was successfully sent") ); public final static FunctionSignature[] signatures = { new FunctionSignature( new QName("send-email", MailModule.NAMESPACE_URI, MailModule.PREFIX), "Sends an email using javax.mail messaging libraries.", new SequenceType[] { new FunctionParameterSequenceType("mail-handle", Type.LONG, Cardinality.EXACTLY_ONE, "The JavaMail session handle retrieved from mail:get-mail-session()"), new FunctionParameterSequenceType("email", Type.ELEMENT, Cardinality.ONE_OR_MORE, "The email message in the following format: <mail> <from/> <reply-to/> <to/> <cc/> <bcc/> <subject/> <message> <text/> <xhtml/> </message> <attachment filename=\"\" mimetype=\"\">xs:base64Binary</attachment> </mail>.") }, new SequenceType(Type.ITEM, Cardinality.EMPTY_SEQUENCE) ) }; public SendEmailFunction(final XQueryContext context, final FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException { if (args.length == 3) { return deprecatedSendEmail(args, contextSequence); } else { return sendEmail(args, contextSequence); } } public Sequence sendEmail(final Sequence[] args, final Sequence contextSequence) throws XPathException { // was a session handle specified? if (args[0].isEmpty()) { throw new XPathException(this, "Session handle not specified"); } // get the Session final long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); final Session session = MailModule.retrieveSession(context, sessionHandle); if (session == null) { throw new XPathException(this, "Invalid Session handle specified"); } try { final Message[] messages = parseInputEmails(session, args[1]); String proto = session.getProperty("mail.transport.protocol"); if (proto == null) { proto = "smtp"; } try (final Transport t = session.getTransport(proto)) { if (session.getProperty("mail." + proto + ".auth") != null) { t.connect(session.getProperty("mail." + proto + ".user"), session.getProperty("mail." + proto + ".password")); } else { t.connect(); } for (final Message msg : messages) { t.sendMessage(msg, msg.getAllRecipients()); } } return Sequence.EMPTY_SEQUENCE; } catch (final TransformerException e) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + e.getMessage(), e); } catch (final MessagingException e) { throw new XPathException(this, "Could not send message(s): " + e.getMessage(), e); } catch (final IOException e) { throw new XPathException(this, "Attachment in some message could not be prepared: " + e.getMessage(), e); } catch (final Throwable t) { throw new XPathException(this, "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(), t); } } public Sequence deprecatedSendEmail(final Sequence[] args, final Sequence contextSequence) throws XPathException { try { //get the charset parameter, default to UTF-8 final String charset; if (!args[2].isEmpty()) { charset = args[2].getStringValue(); } else { charset = "UTF-8"; } // Parse the XML <mail> Elements into mail Objects final int len = args[0].getItemCount(); final Element[] mailElements = new Element[len]; for (int i = 0; i < len; i++) { mailElements[i] = (Element) args[0].itemAt(i); } final Mail[] mails = parseMailElement(mailElements); final ValueSequence results = new ValueSequence(); //Send email with Sendmail or SMTP? if (!args[1].isEmpty()) { //SMTP final boolean[] mailResults = sendBySMTP(mails, args[1].getStringValue(), charset); for (final boolean mailResult : mailResults) { results.add(BooleanValue.valueOf(mailResult)); } } else { for (final Mail mail : mails) { final boolean result = sendBySendmail(mail, charset); results.add(BooleanValue.valueOf(result)); } } return results; } catch (final TransformerException | IOException e) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + e.getMessage(), e); } catch (final SMTPException e) { throw new XPathException(this, "Could not send message(s)" + e.getMessage(), e); } } private Message[] parseInputEmails(final Session session, final Sequence arg) throws IOException, MessagingException, TransformerException { // Parse the XML <mail> Elements into mail Objects final int len = arg.getItemCount(); final Element[] mailElements = new Element[len]; for (int i = 0; i < len; i++) { mailElements[i] = (Element) arg.itemAt(i); } return parseMessageElement(session, mailElements); } /** * Sends an email using the Operating Systems sendmail application * * @param mail representation of the email to send * @param charset the character set * @return boolean value of true of false indicating success or failure to send email */ private boolean sendBySendmail(final Mail mail, final String charset) { //Create a list of all Recipients, should include to, cc and bcc recipient final List<String> allrecipients = new ArrayList<>(); allrecipients.addAll(mail.getTo()); allrecipients.addAll(mail.getCC()); allrecipients.addAll(mail.getBCC()); //Get a string of all recipients email addresses final StringBuilder recipients = new StringBuilder(); for (final String recipient : allrecipients) { recipients.append(" "); //Check format of to address does it include a name as well as the email address? if (recipient.contains("<")) { //yes, just add the email address recipients.append(recipient, recipient.indexOf("<") + 1, recipient.indexOf(">")); } else { //add the email address recipients.append(recipient); } } try { //Create a sendmail Process final Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail" + recipients); //Get a Buffered Print Writer to the Processes stdOut try (final PrintWriter out = new PrintWriter(new OutputStreamWriter(p.getOutputStream(), charset))) { //Send the Message writeMessage(out, mail, false, charset); } } catch (final IOException e) { LOGGER.error(e.getMessage(), e); return false; } // Message Sent Succesfully if (LOGGER.isDebugEnabled()) { LOGGER.debug("send-email() message sent using Sendmail {}", new Date()); } return true; } private static class SMTPException extends Exception { private static final long serialVersionUID = 4859093648476395159L; public SMTPException(final String message) { super(message); } public SMTPException(final Throwable cause) { super(cause); } } /** * Sends an email using SMTP * * @param mails A list of mail object representing the email to send * @param smtpServerArg The SMTP Server to send the email through * @param charset the character set * @return boolean value of true of false indicating success or failure to send email * @throws SMTPException if an I/O error occurs */ private boolean[] sendBySMTP(final Mail[] mails, final String smtpServerArg, final String charset) throws SMTPException { String smtpHost = "localhost"; int smtpPort = 25; if (smtpServerArg != null && !smtpServerArg.isEmpty()) { final int idx = smtpServerArg.indexOf(':'); if (idx > -1) { smtpHost = smtpServerArg.substring(0, idx); smtpPort = Integer.parseInt(smtpServerArg.substring(idx + 1)); } else { smtpHost = smtpServerArg; } } String smtpResult; //Holds the server Result code when an SMTP Command is executed final boolean[] sendMailResults = new boolean[mails.length]; try ( //Create a Socket and connect to the SMTP Server final Socket smtpSock = new Socket(smtpHost, smtpPort); //Create a Buffered Reader for the Socket final BufferedReader smtpIn = new BufferedReader(new InputStreamReader(smtpSock.getInputStream())); //Create an Output Writer for the Socket final PrintWriter smtpOut = new PrintWriter(new OutputStreamWriter(smtpSock.getOutputStream(), charset))) { //First line sent to us from the SMTP server should be "220 blah blah", 220 indicates okay smtpResult = smtpIn.readLine(); if (!smtpResult.startsWith("220")) { final String errMsg = "Error - SMTP Server not ready: '" + smtpResult + "'"; LOGGER.error(errMsg); throw new SMTPException(errMsg); } //Say "HELO" smtpOut.print("HELO " + InetAddress.getLocalHost().getHostName() + "\r\n"); smtpOut.flush(); //get "HELLO" response, should be "250 blah blah" smtpResult = smtpIn.readLine(); if (smtpResult == null) { final String errMsg = "Error - Unexpected null response to SMTP HELO"; LOGGER.error(errMsg); throw new SMTPException(errMsg); } if (!smtpResult.startsWith("250")) { final String errMsg = "Error - SMTP HELO Failed: '" + smtpResult + "'"; LOGGER.error(errMsg); throw new SMTPException(errMsg); } //write SMTP message(s) for (int i = 0; i < mails.length; i++) { final boolean mailResult = writeSMTPMessage(mails[i], smtpOut, smtpIn, charset); sendMailResults[i] = mailResult; } } catch (final IOException ioe) { LOGGER.error(ioe.getMessage(), ioe); throw new SMTPException(ioe); } //Message(s) Sent Succesfully if (LOGGER.isDebugEnabled()) { LOGGER.debug("send-email() message(s) sent using SMTP {}", new Date()); } return sendMailResults; } private boolean writeSMTPMessage(final Mail mail, final PrintWriter smtpOut, final BufferedReader smtpIn, final String charset) { try { String smtpResult; //Send "MAIL FROM:" //Check format of from address does it include a name as well as the email address? if (mail.getFrom().contains("<")) { //yes, just send the email address smtpOut.print("MAIL FROM:<" + mail.getFrom().substring(mail.getFrom().indexOf("<") + 1, mail.getFrom().indexOf(">")) + ">\r\n"); } else { //no, doesnt include a name so send the email address smtpOut.print("MAIL FROM:<" + mail.getFrom() + ">\r\n"); } smtpOut.flush(); //Get "MAIL FROM:" response smtpResult = smtpIn.readLine(); if (smtpResult == null) { LOGGER.error("Error - Unexpected null response to SMTP MAIL FROM"); return false; } if (!smtpResult.startsWith("250")) { LOGGER.error("Error - SMTP MAIL FROM failed: {}", smtpResult); return false; } //RCPT TO should be issued for each to, cc and bcc recipient final List<String> allrecipients = new ArrayList<>(); allrecipients.addAll(mail.getTo()); allrecipients.addAll(mail.getCC()); allrecipients.addAll(mail.getBCC()); for (final String recipient : allrecipients) { //Send "RCPT TO:" //Check format of to address does it include a name as well as the email address? if (recipient.contains("<")) { //yes, just send the email address smtpOut.print("RCPT TO:<" + recipient.substring(recipient.indexOf("<") + 1, recipient.indexOf(">")) + ">\r\n"); } else { smtpOut.print("RCPT TO:<" + recipient + ">\r\n"); } smtpOut.flush(); //Get "RCPT TO:" response smtpResult = smtpIn.readLine(); if (!smtpResult.startsWith("250")) { LOGGER.error("Error - SMTP RCPT TO failed: {}", smtpResult); } } //SEND "DATA" smtpOut.print("DATA\r\n"); smtpOut.flush(); //Get "DATA" response, should be "354 blah blah" (optionally preceded by "250 OK") smtpResult = smtpIn.readLine(); if (smtpResult.startsWith("250")) { // should then be followed by "354 blah blah" smtpResult = smtpIn.readLine(); } if (!smtpResult.startsWith("354")) { LOGGER.error("Error - SMTP DATA failed: {}", smtpResult); return false; } //Send the Message writeMessage(smtpOut, mail, true, charset); //Get end message response, should be "250 blah blah" smtpResult = smtpIn.readLine(); if (!smtpResult.startsWith("250")) { LOGGER.error("Error - Message not accepted: {}", smtpResult); return false; } } catch (final IOException e) { LOGGER.error(e.getMessage(), e); return false; } return true; } /** * Writes an email payload (Headers + Body) from a mail object. * * Access is package-private for unit testing purposes. * * @param out A PrintWriter to receive the email * @param aMail A mail object representing the email to write out * @param useCrLf true to use CRLF for line ending, false to use LF * @param charset the character set * @throws IOException if an I/O error occurs */ static void writeMessage(final PrintWriter out, final Mail aMail, final boolean useCrLf, final String charset) throws IOException { final String eol = useCrLf ? "\r\n" : "\n"; //write the message headers out.print("From: " + encode64Address(aMail.getFrom(), charset) + eol); if (aMail.getReplyTo() != null) { out.print("Reply-To: " + encode64Address(aMail.getReplyTo(), charset) + eol); } for (int x = 0; x < aMail.countTo(); x++) { out.print("To: " + encode64Address(aMail.getTo(x), charset) + eol); } for (int x = 0; x < aMail.countCC(); x++) { out.print("CC: " + encode64Address(aMail.getCC(x), charset) + eol); } for (int x = 0; x < aMail.countBCC(); x++) { out.print("BCC: " + encode64Address(aMail.getBCC(x), charset) + eol); } out.print("Date: " + getDateRFC822() + eol); String subject = aMail.getSubject(); if (subject == null) { subject = ""; } out.print("Subject: " + encode64(subject, charset) + eol); out.print("X-Mailer: eXist-db " + Version.getVersion() + " mail:send-email()" + eol); out.print("MIME-Version: 1.0" + eol); boolean multipartAlternative = false; String multipartBoundary = null; if (aMail.attachmentIterator().hasNext()) { // we have an attachment as well as text and/or html, so we need a multipart/mixed message multipartBoundary = multipartBoundary(1); } else if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML())) { // we have text and html, so we need a multipart/alternative message and no attachment multipartAlternative = true; multipartBoundary = multipartBoundary(1) + "_alt"; } // else { // // we have either text or html and no attachment this message is not multipart //content type if (multipartBoundary != null) { //multipart message out.print("Content-Type: " + (multipartAlternative ? "multipart/alternative" : "multipart/mixed") + "; boundary=" + parameterValue(multipartBoundary) + eol); //Mime warning out.print(eol); out.print(ERROR_MSG_NON_MIME_CLIENT + eol); out.print(eol); out.print("--" + multipartBoundary + eol); } if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML()) && aMail.attachmentIterator().hasNext()) { out.print("Content-Type: multipart/alternative; boundary=" + parameterValue(multipartBoundary(1) + "_alt") + eol); out.print(eol); out.print("--" + multipartBoundary(1) + "_alt" + eol); } //text email if (nonEmpty(aMail.getText())) { out.print("Content-Type: text/plain; charset=" + charset + eol); out.print("Content-Transfer-Encoding: 8bit" + eol); //now send the txt message out.print(eol); out.print(aMail.getText() + eol); if (multipartBoundary != null) { if (nonEmpty(aMail.getXHTML()) || aMail.attachmentIterator().hasNext()) { if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML()) && aMail.attachmentIterator().hasNext()) { out.print("--" + multipartBoundary(1) + "_alt" + eol); } else { out.print("--" + multipartBoundary + eol); } } else { if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML()) && aMail.attachmentIterator().hasNext()) { out.print("--" + multipartBoundary(1) + "_alt--" + eol); } else { out.print("--" + multipartBoundary + "--" + eol); } } } } //HTML email if (nonEmpty(aMail.getXHTML())) { out.print("Content-Type: text/html; charset=" + charset + eol); out.print("Content-Transfer-Encoding: 8bit" + eol); //now send the html message out.print(eol); out.print("<!DOCTYPE html PUBLIC \"- out.print(aMail.getXHTML() + eol); if (multipartBoundary != null) { if (aMail.attachmentIterator().hasNext()) { if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML()) && aMail.attachmentIterator().hasNext()) { out.print("--" + multipartBoundary(1) + "_alt--" + eol); out.print("--" + multipartBoundary + eol); } else { out.print("--" + multipartBoundary + eol); } } else { if (nonEmpty(aMail.getText()) && nonEmpty(aMail.getXHTML()) && aMail.attachmentIterator().hasNext()) { out.print("--" + multipartBoundary(1) + "_alt--" + eol); } else { out.print("--" + multipartBoundary + "--" + eol); } } } } //attachments if (aMail.attachmentIterator().hasNext()) { for (final Iterator<MailAttachment> itAttachment = aMail.attachmentIterator(); itAttachment.hasNext(); ) { final MailAttachment ma = itAttachment.next(); out.print("Content-Type: " + ma.getMimeType() + "; name=" + parameterValue(ma.getFilename()) + eol); out.print("Content-Transfer-Encoding: base64" + eol); out.print("Content-Description: " + ma.getFilename() + eol); out.print("Content-Disposition: attachment; filename=" + parameterValue(ma.getFilename()) + eol); out.print(eol); //write out the attachment encoded data in fixed width lines final char[] buf = new char[MIME_BASE64_MAX_LINE_LENGTH]; int read = -1; final Reader attachmentDataReader = new StringReader(ma.getData()); while ((read = attachmentDataReader.read(buf, 0, MIME_BASE64_MAX_LINE_LENGTH)) > -1) { out.print(String.valueOf(buf, 0, read) + eol); } if (itAttachment.hasNext()) { out.print("--" + multipartBoundary + eol); } } //Emd multipart message out.print("--" + multipartBoundary + "--" + eol); } //end the message, <cr><lf>.<cr><lf> out.print(eol); out.print("." + eol); out.flush(); } /** * Constructs a mail Object from an XML representation of an email * <p> * The XML email Representation is expected to look something like this * * <mail> * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text></text> * <xhtml></xhtml> * </message> * </mail> * * @param mailElements The XML mail Node * @throws TransformerException if a transformation error occurs * @return A mail Object representing the XML mail Node */ private Mail[] parseMailElement(final Element[] mailElements) throws TransformerException, IOException { Mail[] mails = new Mail[mailElements.length]; int i = 0; for (final Element mailElement : mailElements) { //Make sure that message has a Mail node if ("mail".equals(mailElement.getLocalName())) { final Mail mail = new Mail(); //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (Node.ELEMENT_NODE == child.getNodeType() && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": mail.setFrom(child.getFirstChild().getNodeValue()); break; case "reply-to": mail.setReplyTo(child.getFirstChild().getNodeValue()); break; case "to": mail.addTo(child.getFirstChild().getNodeValue()); break; case "cc": mail.addCC(child.getFirstChild().getNodeValue()); break; case "bcc": mail.addBCC(child.getFirstChild().getNodeValue()); break; case "subject": mail.setSubject(child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if ("text".equals(bodyPart.getLocalName())) { mail.setText(bodyPart.getFirstChild().getNodeValue()); } else if ("xhtml".equals(bodyPart.getLocalName())) { //Convert everything inside <xhtml></xhtml> to text final Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); final DOMSource source = new DOMSource(bodyPart.getFirstChild()); try (final StringWriter strWriter = new StringWriter()) { final StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); mail.setXHTML(strWriter.toString()); } } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": final Element attachment = (Element) child; final MailAttachment ma = new MailAttachment(attachment.getAttribute("filename"), attachment.getAttribute("mimetype"), attachment.getFirstChild().getNodeValue()); mail.addAttachment(ma); break; } } //next node child = child.getNextSibling(); } mails[i++] = mail; } } if (i != mailElements.length) { mails = Arrays.copyOf(mails, i); } return mails; } /** * Constructs a mail Object from an XML representation of an email * <p> * The XML email Representation is expected to look something like this * * <mail> * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @throws IOException if an I/O error occurs * @throws MessagingException if an email error occurs * @throws TransformerException if a transformation error occurs * @return A mail Object representing the XML mail Node */ private Message[] parseMessageElement(final Session session, final Element[] mailElements) throws IOException, MessagingException, TransformerException { Message[] mails = new Message[mailElements.length]; int i = 0; for (final Element mailElement : mailElements) { //Make sure that message has a Mail node if ("mail".equals(mailElement.getLocalName())) { //New message Object // create a message final MimeMessage msg = new MimeMessage(session); boolean fromWasSet = false; final List<InternetAddress> replyTo = new ArrayList<>(); MimeBodyPart body = null; Multipart multibody = null; final List<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (Node.ELEMENT_NODE == child.getNodeType() && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address final InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (Node.ELEMENT_NODE != bodyPart.getNodeType()) { continue; } final Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; switch (bodyPart.getLocalName()) { case "text": // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; break; case "xhtml": //Convert everything inside <xhtml></xhtml> to text final Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); final DOMSource source = new DOMSource(bodyPart.getFirstChild()); try (final StringWriter strWriter = new StringWriter()) { final StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); } contentType = "html"; break; case "generic": // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); break; } // Now, time to store it if (content != null && contentType != null && !contentType.isEmpty()) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) { multibody.addBodyPart(body); } } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": final Element attachment = (Element) child; final MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } final StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (Node.ELEMENT_NODE == attachChild.getNodeType()) { final Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); final DOMSource source = new DOMSource(attachChild); try (final StringWriter strWriter = new StringWriter()) { final StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter); } } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) { msg.setFrom(); } msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); // Preparing content and attachments if (!attachments.isEmpty()) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { final MimeMultipart container = new MimeMultipart("mixed"); final MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (final MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails[i++] = msg; } } if (i != mailElements.length) { mails = Arrays.copyOf(mails, i); } return mails; } /** * Returns the current date and time in an RFC822 format, suitable for an email Date Header * * @return RFC822 formated date and time as a String */ private static String getDateRFC822() { String dateString = ""; final Calendar rightNow = Calendar.getInstance(); //Day of the week switch (rightNow.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY: dateString = "Mon"; break; case Calendar.TUESDAY: dateString = "Tue"; break; case Calendar.WEDNESDAY: dateString = "Wed"; break; case Calendar.THURSDAY: dateString = "Thu"; break; case Calendar.FRIDAY: dateString = "Fri"; break; case Calendar.SATURDAY: dateString = "Sat"; break; case Calendar.SUNDAY: dateString = "Sun"; break; } dateString += ", "; //Date dateString += rightNow.get(Calendar.DAY_OF_MONTH); dateString += " "; //Month switch (rightNow.get(Calendar.MONTH)) { case Calendar.JANUARY: dateString += "Jan"; break; case Calendar.FEBRUARY: dateString += "Feb"; break; case Calendar.MARCH: dateString += "Mar"; break; case Calendar.APRIL: dateString += "Apr"; break; case Calendar.MAY: dateString += "May"; break; case Calendar.JUNE: dateString += "Jun"; break; case Calendar.JULY: dateString += "Jul"; break; case Calendar.AUGUST: dateString += "Aug"; break; case Calendar.SEPTEMBER: dateString += "Sep"; break; case Calendar.OCTOBER: dateString += "Oct"; break; case Calendar.NOVEMBER: dateString += "Nov"; break; case Calendar.DECEMBER: dateString += "Dec"; break; } dateString += " "; //Year dateString += rightNow.get(Calendar.YEAR); dateString += " "; //Time String tHour = Integer.toString(rightNow.get(Calendar.HOUR_OF_DAY)); if (tHour.length() == 1) { tHour = "0" + tHour; } String tMinute = Integer.toString(rightNow.get(Calendar.MINUTE)); if (tMinute.length() == 1) { tMinute = "0" + tMinute; } String tSecond = Integer.toString(rightNow.get(Calendar.SECOND)); if (tSecond.length() == 1) { tSecond = "0" + tSecond; } dateString += tHour + ":" + tMinute + ":" + tSecond + " "; //TimeZone Correction final String tzSign; String tzHours = ""; String tzMinutes = ""; final TimeZone thisTZ = rightNow.getTimeZone(); int tzOffset = thisTZ.getOffset(rightNow.getTime().getTime()); //get timezone offset in milliseconds tzOffset = (tzOffset / 1000); //convert to seconds tzOffset = (tzOffset / 60); //convert to minutes //Sign if (tzOffset > 1) { tzSign = "+"; } else { tzSign = "-"; tzOffset *= -1; } //Calc Hours and Minutes? if (tzOffset >= 60) { //Minutes and Hours tzHours += (tzOffset / 60); //hours // do we need to prepend a 0 if (tzHours.length() == 1) { tzHours = "0" + tzHours; } tzMinutes += (tzOffset % 60); //minutes // do we need to prepend a 0 if (tzMinutes.length() == 1) { tzMinutes = "0" + tzMinutes; } } else { //Just Minutes tzHours = "00"; tzMinutes += tzOffset; // do we need to prepend a 0 if (tzMinutes.length() == 1) { tzMinutes = "0" + tzMinutes; } } dateString += tzSign + tzHours + tzMinutes; return dateString; } /** * Base64 Encodes a string (used for message subject). * * Access is package-private for unit testing purposes. * * @param str The String to encode * @throws java.io.UnsupportedEncodingException if the encocding is unsupported * @return The encoded String */ static String encode64(final String str, final String charset) throws java.io.UnsupportedEncodingException { String result = Base64.encodeBase64String(str.getBytes(charset)); result = result.replaceAll("\n", "?=\n =?" + charset + "?B?"); result = "=?" + charset + "?B?" + result + "?="; return result; } /** * Base64 Encodes an email address * * @param str The email address as a String to encode * @param charset the character set * @throws java.io.UnsupportedEncodingException if the encocding is unsupported * @return The encoded email address String */ private static String encode64Address(final String str, final String charset) throws java.io.UnsupportedEncodingException { final int idx = str.indexOf("<"); final String result; if (idx != -1) { result = encode64(str.substring(0, idx), charset) + " " + str.substring(idx); } else { result = str; } return result; } /** * A simple data class to represent an email attachment. * * It doesn't do anything fancy, it just has private * members and get and set methods. * * Access is package-private for unit testing purposes. */ static class MailAttachment { private final String filename; private final String mimeType; private final String data; public MailAttachment(final String filename, final String mimeType, final String data) { this.filename = filename; this.mimeType = mimeType; this.data = data; } public String getData() { return data; } public String getFilename() { return filename; } public String getMimeType() { return mimeType; } } /** * A simple data class to represent an email. * It doesn't do anything fancy, it just has private * members and get and set methods. * * Access is package-private for unit testing purposes. */ static class Mail { private String from; //Who is the mail from private String replyTo; //Who should you reply to private final List<String> to = new ArrayList<>(1); //Who is the mail going to private List<String> cc; //Carbon Copy to private List<String> bcc; //Blind Carbon Copy to private String subject; //Subject of the mail private String text; //Body text of the mail private String xhtml; //Body XHTML of the mail private List<MailAttachment> attachments; //Any attachments //From public void setFrom(final String from) { this.from = from; } public String getFrom() { return this.from; } //reply-to public void setReplyTo(final String replyTo) { this.replyTo = replyTo; } public String getReplyTo() { return replyTo; } public void addTo(final String to) { this.to.add(to); } public int countTo() { return to.size(); } public String getTo(final int index) { return to.get(index); } public List<String> getTo() { return to; } public void addCC(final String cc) { if (this.cc == null) { this.cc = new ArrayList<>(); } this.cc.add(cc); } public int countCC() { if (this.cc == null) { return 0; } return cc.size(); } public String getCC(final int index) { if (this.cc == null) { throw new IndexOutOfBoundsException(); } return cc.get(index); } public List<String> getCC() { if (this.cc == null) { return Collections.EMPTY_LIST; } return cc; } //BCC public void addBCC(final String bcc) { if (this.bcc == null) { this.bcc = new ArrayList<>(); } this.bcc.add(bcc); } public int countBCC() { if (this.bcc == null) { return 0; } return bcc.size(); } public String getBCC(final int index) { if (this.bcc == null) { throw new IndexOutOfBoundsException(); } return bcc.get(index); } public List<String> getBCC() { if (this.bcc == null) { return Collections.EMPTY_LIST; } return bcc; } //Subject public void setSubject(final String subject) { this.subject = subject; } public String getSubject() { return subject; } //text public void setText(final String text) { this.text = text; } public String getText() { return text; } //xhtml public void setXHTML(final String xhtml) { this.xhtml = xhtml; } public String getXHTML() { return xhtml; } public void addAttachment(final MailAttachment ma) { if (this.attachments == null) { this.attachments = new ArrayList<>(); } attachments.add(ma); } public Iterator<MailAttachment> attachmentIterator() { if (this.attachments == null) { return Collections.EMPTY_LIST.iterator(); } return attachments.iterator(); } } private static boolean nonEmpty(@Nullable final String str) { return str != null && !str.isEmpty(); } /** * Creates a "quoted-string" of the parameter value * if it contains a non-token value (See {@link #isNonToken(String)}), * otherwise it returns the parameter value as is. * * Access is package-private for unit testing purposes. * * @param value parameter value. * * @return the quoted string parameter value, or the parameter value as is. */ static String parameterValue(final String value) { if (isNonToken(value)) { return "\"" + value + "\""; } else { return value; } } private static boolean isNonToken(final String str) { return NON_TOKEN_PATTERN.matcher(str).matches(); } /** * Produce a multi-part boundary string. * * Access is package-private for unit testing purposes. * * @param multipartInstance the number of this multipart instance. * * @return the multi-part boundary string. */ static String multipartBoundary(final int multipartInstance) { // Get the version of eXist-db final String version = Version.getVersion(); return "eXist-db.multipart." + version + "_multipart_" + multipartInstance; } }
package nl.xservices.plugins; import android.annotation.SuppressLint; import android.app.Activity; import android.content.*; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Build; import android.text.Html; import android.util.Base64; import android.view.Gravity; import android.widget.Toast; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SocialSharing extends CordovaPlugin { private static final String ACTION_AVAILABLE_EVENT = "available"; private static final String ACTION_SHARE_EVENT = "share"; private static final String ACTION_CAN_SHARE_VIA = "canShareVia"; private static final String ACTION_CAN_SHARE_VIA_EMAIL = "canShareViaEmail"; private static final String ACTION_SHARE_VIA = "shareVia"; private static final String ACTION_SHARE_VIA_TWITTER_EVENT = "shareViaTwitter"; private static final String ACTION_SHARE_VIA_FACEBOOK_EVENT = "shareViaFacebook"; private static final String ACTION_SHARE_VIA_FACEBOOK_WITH_PASTEMESSAGEHINT = "shareViaFacebookWithPasteMessageHint"; private static final String ACTION_SHARE_VIA_WHATSAPP_EVENT = "shareViaWhatsApp"; private static final String ACTION_SHARE_VIA_SMS_EVENT = "shareViaSMS"; private static final String ACTION_SHARE_VIA_EMAIL_EVENT = "shareViaEmail"; private static final int ACTIVITY_CODE_SENDVIAEMAIL = 2; private CallbackContext _callbackContext; private String pasteMessage; private abstract class SocialSharingRunnable implements Runnable { public CallbackContext callbackContext; SocialSharingRunnable(CallbackContext cb) { this.callbackContext = cb; } } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this._callbackContext = callbackContext; // only used for onActivityResult this.pasteMessage = null; if (ACTION_AVAILABLE_EVENT.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else if (ACTION_SHARE_EVENT.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), null, false); } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "twitter", false); } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "com.facebook.katana", false); } else if (ACTION_SHARE_VIA_FACEBOOK_WITH_PASTEMESSAGEHINT.equals(action)) { this.pasteMessage = args.getString(4); return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "com.facebook.katana", false); } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "whatsapp", false); } else if (ACTION_CAN_SHARE_VIA.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), true); } else if (ACTION_CAN_SHARE_VIA_EMAIL.equals(action)) { if (isEmailAvailable()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "not available")); return false; } } else if (ACTION_SHARE_VIA.equals(action)) { return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), false); } else if (ACTION_SHARE_VIA_SMS_EVENT.equals(action)) { return invokeSMSIntent(callbackContext, args.getJSONObject(0), args.getString(1)); } else if (ACTION_SHARE_VIA_EMAIL_EVENT.equals(action)) { return invokeEmailIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.isNull(3) ? null : args.getJSONArray(3), args.isNull(4) ? null : args.getJSONArray(4), args.isNull(5) ? null : args.getJSONArray(5)); } else { callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); return false; } } private boolean isEmailAvailable() { final Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "someone@domain.com", null)); return cordova.getActivity().getPackageManager().queryIntentActivities(intent, 0).size() > 0; } private boolean invokeEmailIntent(final CallbackContext callbackContext, final String message, final String subject, final JSONArray to, final JSONArray cc, final JSONArray bcc, final JSONArray files) throws JSONException { final SocialSharing plugin = this; cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) { public void run() { final Intent draft = new Intent(Intent.ACTION_SEND_MULTIPLE); if (notEmpty(message)) { Pattern htmlPattern = Pattern.compile(".*\\<[^>]+>.*", Pattern.DOTALL); if (htmlPattern.matcher(message).matches()) { draft.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(message)); draft.setType("text/html"); } else { draft.putExtra(android.content.Intent.EXTRA_TEXT, message); draft.setType("text/plain"); } } if (notEmpty(subject)) { draft.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); } try { if (to != null && to.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_EMAIL, toStringArray(to)); } if (cc != null && cc.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_CC, toStringArray(cc)); } if (bcc != null && bcc.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_BCC, toStringArray(bcc)); } if (files.length() > 0) { ArrayList<Uri> fileUris = new ArrayList<Uri>(); final String dir = getDownloadDir(); for (int i = 0; i < files.length(); i++) { final Uri fileUri = getFileUriAndSetType(draft, dir, files.getString(i), subject, i); if (fileUri != null) { fileUris.add(fileUri); } } if (!fileUris.isEmpty()) { draft.putExtra(Intent.EXTRA_STREAM, fileUris); } } } catch (Exception e) { callbackContext.error(e.getMessage()); } draft.setType("application/octet-stream"); cordova.startActivityForResult(plugin, Intent.createChooser(draft, "Choose Email App"), ACTIVITY_CODE_SENDVIAEMAIL); } }); return true; } private String getDownloadDir() throws IOException { final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; // external createOrCleanDir(dir); return dir; } private boolean doSendIntent(final CallbackContext callbackContext, final String msg, final String subject, final JSONArray files, final String url, final String appPackageName, final boolean peek) { final CordovaInterface mycordova = cordova; final CordovaPlugin plugin = this; cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) { public void run() { String message = msg; final boolean hasMultipleAttachments = files.length() > 1; final Intent sendIntent = new Intent(hasMultipleAttachments ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SEND); sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); try { if (files.length() > 0 && !"".equals(files.getString(0))) { ArrayList<Uri> fileUris = new ArrayList<Uri>(); final String dir = getDownloadDir(); Uri fileUri = null; for (int i = 0; i < files.length(); i++) { fileUri = getFileUriAndSetType(sendIntent, dir, files.getString(i), subject, i); if (fileUri != null) { fileUris.add(fileUri); } } if (!fileUris.isEmpty()) { if (hasMultipleAttachments) { sendIntent.putExtra(Intent.EXTRA_STREAM, fileUris); } else { sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri); } } } else{ sendIntent.setType("text/plain"); } } catch(Exception e){ callbackContext.error(e.getMessage()); } if (notEmpty(subject)) { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } // add the URL to the message, as there seems to be no separate field if (notEmpty(url)) { if (notEmpty(message)) { message += " " + url; } else { message = url; } } if (notEmpty(message)) { sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); sendIntent.putExtra("sms_body", message); // sometimes required when the user picks share via sms } if (appPackageName != null) { String packageName = appPackageName; String passedActivityName = null; if (packageName.contains("/")) { String[] items = appPackageName.split("/"); packageName = items[0]; passedActivityName = items[1]; } final ActivityInfo activity = getActivity(callbackContext, sendIntent, packageName); if (activity != null) { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, passedActivityName != null ? passedActivityName : activity.name)); mycordova.startActivityForResult(plugin, sendIntent, 0); if (pasteMessage != null) { // add a little delay because target app (facebook only atm) needs to be started first new Timer().schedule(new TimerTask() { public void run() { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { showPasteMessage(msg, pasteMessage); } }); } }, 2000); } } } } else { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { mycordova.startActivityForResult(plugin, Intent.createChooser(sendIntent, null), 1); } } } }); return true; } @SuppressLint("NewApi") private void showPasteMessage(String msg, String label) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return; } // copy to clipboard final ClipboardManager clipboard = (android.content.ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE); final ClipData clip = android.content.ClipData.newPlainText(label, msg); clipboard.setPrimaryClip(clip); // show a toast final Toast toast = Toast.makeText(webView.getContext(), label, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } private Uri getFileUriAndSetType(Intent sendIntent, String dir, String image, String subject, int nthFile) throws IOException { // we're assuming an image, but this can be any filetype you like String localImage = image; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(url); if (m.find()) { return m.group(1); } else { return null; } } private byte[] getBytes(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(5000); int current; while ((current = bis.read()) != -1) { baf.append((byte) current); } return baf.toByteArray(); } private void saveFile(byte[] bytes, String dirName, String fileName) throws IOException { final File dir = new File(dirName); final FileOutputStream fos = new FileOutputStream(new File(dir, fileName)); fos.write(bytes); fos.flush(); fos.close(); } /** * As file.deleteOnExit does not work on Android, we need to delete files manually. * Deleting them in onActivityResult is not a good idea, because for example a base64 encoded file * will not be available for upload to Facebook (it's deleted before it's uploaded). * So the best approach is deleting old files when saving (sharing) a new one. */ private void cleanupOldFiles(File dir) { for (File f : dir.listFiles()) { //noinspection ResultOfMethodCallIgnored f.delete(); } } private static boolean notEmpty(String what) { return what != null && !"".equals(what) && !"null".equalsIgnoreCase(what); } private static String[] toStringArray(JSONArray jsonArray) throws JSONException { String[] result = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { result[i] = jsonArray.getString(i); } return result; } public static String sanitizeFilename(String name) {
package nl.xservices.plugins; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Build; import android.text.Html; import android.util.Base64; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SocialSharing extends CordovaPlugin { private static final String ACTION_AVAILABLE_EVENT = "available"; private static final String ACTION_SHARE_EVENT = "share"; private static final String ACTION_CAN_SHARE_VIA = "canShareVia"; private static final String ACTION_CAN_SHARE_VIA_EMAIL = "canShareViaEmail"; private static final String ACTION_SHARE_VIA = "shareVia"; private static final String ACTION_SHARE_VIA_TWITTER_EVENT = "shareViaTwitter"; private static final String ACTION_SHARE_VIA_FACEBOOK_EVENT = "shareViaFacebook"; private static final String ACTION_SHARE_VIA_WHATSAPP_EVENT = "shareViaWhatsApp"; private static final String ACTION_SHARE_VIA_SMS_EVENT = "shareViaSMS"; private static final String ACTION_SHARE_VIA_EMAIL_EVENT = "shareViaEmail"; private static final int ACTIVITY_CODE_SENDVIAEMAIL = 2; private CallbackContext callbackContext; private abstract class SocialSharingRunnable implements Runnable { public CallbackContext callbackContext; SocialSharingRunnable(CallbackContext cb) { this.callbackContext = cb; } } @Override public boolean execute(String action, JSONArray args, CallbackContext pCallbackContext) throws JSONException { this.callbackContext = pCallbackContext; if (ACTION_AVAILABLE_EVENT.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else if (ACTION_SHARE_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), null, false); } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "twitter", false); } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "com.facebook.katana", false); } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "whatsapp", false); } else if (ACTION_CAN_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), true); } else if (ACTION_CAN_SHARE_VIA_EMAIL.equals(action)) { if (isEmailAvailable()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "not available")); return false; } } else if (ACTION_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), false); } else if (ACTION_SHARE_VIA_SMS_EVENT.equals(action)) { return invokeSMSIntent(args.getString(0), args.getString(1)); } else if (ACTION_SHARE_VIA_EMAIL_EVENT.equals(action)) { return invokeEmailIntent(args.getString(0), args.getString(1), args.getJSONArray(2), args.isNull(3) ? null : args.getJSONArray(3), args.isNull(4) ? null : args.getJSONArray(4), args.isNull(5) ? null : args.getJSONArray(5)); } else { callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); return false; } } private boolean isEmailAvailable() { final Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "someone@domain.com", null)); return cordova.getActivity().getPackageManager().queryIntentActivities(intent, 0).size() > 1; } private boolean invokeEmailIntent(final String message, final String subject, final JSONArray to, final JSONArray cc, final JSONArray bcc, final JSONArray files) throws JSONException { final SocialSharing plugin = this; cordova.getThreadPool().execute(new SocialSharingRunnable(this.callbackContext) { public void run() { final Intent draft = new Intent(Intent.ACTION_SEND_MULTIPLE); if (notEmpty(message)) { if (message.matches(".*<[^>]+>.*")) { draft.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(message)); draft.setType("text/html"); } else { draft.putExtra(android.content.Intent.EXTRA_TEXT, message); draft.setType("text/plain"); } } if (notEmpty(subject)) { draft.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); } try { if (to != null && to.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_EMAIL, toStringArray(to)); } if (cc != null && cc.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_CC, toStringArray(cc)); } if (bcc != null && bcc.length() > 0) { draft.putExtra(android.content.Intent.EXTRA_BCC, toStringArray(bcc)); } if (files.length() > 0) { ArrayList<Uri> fileUris = new ArrayList<Uri>(); final String dir = getDownloadDir(); for (int i = 0; i < files.length(); i++) { final Uri fileUri = getFileUriAndSetType(draft, dir, files.getString(i), subject); if (fileUri != null) { fileUris.add(fileUri); } } if (!fileUris.isEmpty()) { draft.putExtra(Intent.EXTRA_STREAM, fileUris); } } } catch (Exception e) { callbackContext.error(e.getMessage()); } draft.setType("application/octet-stream"); cordova.startActivityForResult(plugin, Intent.createChooser(draft, "Choose Email App"), ACTIVITY_CODE_SENDVIAEMAIL); } }); return true; } private String getDownloadDir() throws IOException { final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; createOrCleanDir(dir); return dir; } private boolean doSendIntent(final String msg, final String subject, final JSONArray files, final String url, final String appPackageName, final boolean peek) { final CordovaInterface mycordova = cordova; final CordovaPlugin plugin = this; cordova.getThreadPool().execute(new SocialSharingRunnable(this.callbackContext) { public void run() { String message = msg; final boolean hasMultipleAttachments = files.length() > 1; final Intent sendIntent = new Intent(hasMultipleAttachments ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SEND); sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); if (files.length() > 0) { ArrayList<Uri> fileUris = new ArrayList<Uri>(); try { final String dir = getDownloadDir(); Uri fileUri = null; for (int i = 0; i < files.length(); i++) { fileUri = getFileUriAndSetType(sendIntent, dir, files.getString(i), subject); if (fileUri != null) { fileUris.add(fileUri); } } if (!fileUris.isEmpty()) { if (hasMultipleAttachments) { sendIntent.putExtra(Intent.EXTRA_STREAM, fileUris); } else { sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri); } } } catch (Exception e) { callbackContext.error(e.getMessage()); } } else { sendIntent.setType("text/plain"); } if (notEmpty(subject)) { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } // add the URL to the message, as there seems to be no separate field if (notEmpty(url)) { if (notEmpty(message)) { message += " " + url; } else { message = url; } } if (notEmpty(message)) { sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); } if (appPackageName != null) { final ActivityInfo activity = getActivity(sendIntent, appPackageName); if (activity != null) { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, activity.name)); mycordova.startActivityForResult(plugin, sendIntent, 0); } } } else { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { mycordova.startActivityForResult(plugin, Intent.createChooser(sendIntent, null), 1); } } } }); return true; } private Uri getFileUriAndSetType(Intent sendIntent, String dir, String image, String subject) throws IOException { // we're assuming an image, but this can be any filetype you like String localImage = image; /** * As file.deleteOnExit does not work on Android, we need to delete files manually. * Deleting them in onActivityResult is not a good idea, because for example a base64 encoded file * will not be available for upload to Facebook (it's deleted before it's uploaded). * So the best approach is deleting old files when saving (sharing) a new one. */ private void cleanupOldFiles(File dir) { for (File f : dir.listFiles()) { //noinspection ResultOfMethodCallIgnored f.delete(); } } private static boolean notEmpty(String what) { return what != null && !"".equals(what) && !"null".equalsIgnoreCase(what); } private static String[] toStringArray(JSONArray jsonArray) throws JSONException { String[] result = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { result[i] = jsonArray.getString(i); } return result; } public static String sanitizeFilename(String name) {
package android.palharini.myhealth.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.palharini.myhealth.R; import android.palharini.myhealth.activities.edit.PreferencesEdit; import android.palharini.myhealth.activities.edit.UserEdit; import android.palharini.myhealth.activities.register.IndicatorRegister; import android.palharini.myhealth.db.dao.IndicatorDAO; import android.palharini.myhealth.db.dao.UserDAO; import android.palharini.myhealth.db.entities.Indicator; import android.palharini.myhealth.db.entities.User; import android.palharini.myhealth.session.SessionManager; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main extends Activity { private SessionManager session; private UserDAO usrDAO; private User user; private IndicatorDAO indDAO; private Indicator indHeight, indWeight, indicator; private TextView tvHello, tvBMI, tvStatusBMI, tvTargetBPM; private Button btInsIndicator, btMonitoring, btUserInfo, btSettings; private ArrayList<Indicator> arrayIndicators; private List<String> listRangesBMI; private String stName, stFirstName, vtFaixasIMC[]; private Double dbHeight, dbWeight, dbBMI; private Integer intAge; // Heart Rate measures private Integer intRestingBPM, intFinalRestingBPM, intAvgRestingBPM, intMaxBPM, intReserveBPM, intMinTargetBPM, intMaxTargetBPM, intTargetBPM; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // TODO Isolate data processing threads from UI thread if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } tvHello = (TextView) findViewById(R.id.tvOla); tvBMI = (TextView) findViewById(R.id.IMC); tvStatusBMI = (TextView) findViewById(R.id.tvStatusIMC); tvTargetBPM = (TextView) findViewById(R.id.alvoBPM); btInsIndicator = (Button) findViewById(R.id.btCadIndicador); btMonitoring = (Button) findViewById(R.id.btAcompanhamento); btUserInfo = (Button) findViewById(R.id.btDados); btSettings = (Button) findViewById(R.id.btConfiguracoes); session = new SessionManager(getApplicationContext()); usrDAO = new UserDAO(); indDAO = new IndicatorDAO(); setNomeUsuario(); calcularIMC(); calcularBPMIdeal(); btInsIndicator.setOnClickListener(new Button.OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent irTelaCadIndicador = new Intent(getApplicationContext(), IndicatorRegister.class); startActivity(irTelaCadIndicador); } }); btMonitoring.setOnClickListener(new Button.OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent irTelaAcompanhamento = new Intent(getApplicationContext(), IndicatorTypesList.class); startActivity(irTelaAcompanhamento); } }); btUserInfo.setOnClickListener(new Button.OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent irTelaEdicaoUsuario = new Intent(getApplicationContext(), UserEdit.class); startActivity(irTelaEdicaoUsuario); } }); btSettings.setOnClickListener(new Button.OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent irTelaConfiguracoes = new Intent(getApplicationContext(), PreferencesEdit.class); startActivity(irTelaConfiguracoes); } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.onWindowFocusChanged(hasFocus); setNomeUsuario(); calcularIMC(); calcularBPMIdeal(); } public void setNomeUsuario () { user = usrDAO.buscarUsuario(session.getIdUsuario()); stName = user.getNome(); if (stName.contains(" ")) { stFirstName = stName.substring(0, stName.indexOf(" ")); } else { stFirstName = stName; } tvHello.setText(getString(R.string.tvOla) + " " + stFirstName); } public void calcularIMC () { indHeight = indDAO.buscarIndicadorTipo(session.getIdUsuario(), 0, 1); indWeight = indDAO.buscarIndicadorTipo(session.getIdUsuario(), 1, 1); dbWeight = indWeight.getMedida1(); dbHeight = indHeight.getMedida1(); dbHeight = dbHeight /100; dbBMI = (dbWeight / (dbHeight * dbHeight)); DecimalFormat decimal = new DecimalFormat("0.0"); tvBMI.setText(decimal.format(dbBMI)); vtFaixasIMC = getResources().getStringArray(R.array.faixasIMC); listRangesBMI = Arrays.asList(vtFaixasIMC); if (dbBMI > 0 && dbBMI <= 18.5) tvStatusBMI.setText(listRangesBMI.get(0)); if (dbBMI >= 18.6 && dbBMI <= 24.9) tvStatusBMI.setText(listRangesBMI.get(1)); if (dbBMI >= 25 && dbBMI <= 29.9) tvStatusBMI.setText(listRangesBMI.get(2)); if (dbBMI >= 30 && dbBMI <= 34.9) tvStatusBMI.setText(listRangesBMI.get(3)); if (dbBMI >= 35 && dbBMI <= 39.9) tvStatusBMI.setText(listRangesBMI.get(4)); if (dbBMI >= 40) tvStatusBMI.setText(listRangesBMI.get(5)); } public void calcularBPMIdeal () { intAge = usrDAO.buscarIdadeUsuario(session.getIdUsuario()); arrayIndicators = indDAO.buscarIndicadoresTipo(session.getIdUsuario(), 2); intFinalRestingBPM =0; if (arrayIndicators.size() >= 3) { int x; for (x=1; x<=3; x++) { indicator = arrayIndicators.get(x); intRestingBPM = indicator.getMedida1().intValue(); intFinalRestingBPM = intFinalRestingBPM + intRestingBPM; } intAvgRestingBPM = intFinalRestingBPM / 3; intMaxBPM = 220 - intAge; intReserveBPM = intMaxBPM - intAvgRestingBPM; intMinTargetBPM = (intReserveBPM * (60 / 100)) + intAvgRestingBPM; intMaxTargetBPM = (intReserveBPM * (80 / 100)) + intAvgRestingBPM; intTargetBPM = (intMinTargetBPM + intMaxTargetBPM) / 2; tvTargetBPM.setText(intTargetBPM + " BPM"); } } }
package com.evolveum.midpoint.web.page.login; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.feedback.ContainerFeedbackMessageFilter; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.image.Image; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.string.StringValue; import com.evolveum.midpoint.common.policy.ValuePolicyGenerator; import com.evolveum.midpoint.gui.api.component.captcha.CaptchaPanel; import com.evolveum.midpoint.gui.api.component.password.PasswordPanel; import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.Producer; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.application.PageDescriptor; import com.evolveum.midpoint.web.component.AjaxButton; import com.evolveum.midpoint.web.component.AjaxSubmitButton; import com.evolveum.midpoint.web.component.form.Form; import com.evolveum.midpoint.web.component.input.TextPanel; import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnBlurAjaxFormUpdatingBehaviour; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceCredentialsPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; //+ "/token=" + userType.getCostCenter() + "/roleId=00000000-0000-0000-0000-000000000008"; @PageDescriptor(url = "/registration") public class PageSelfRegistration extends PageRegistrationBase { private static final Trace LOGGER = TraceManager.getTrace(PageSelfRegistration.class); private static final String DOT_CLASS = PageSelfRegistration.class.getName() + "."; private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_FIRST_NAME = "firstName"; private static final String ID_LAST_NAME = "lastName"; private static final String ID_EMAIL = "email"; private static final String ID_PASSWORD = "password"; private static final String ID_SUBMIT_REGISTRATION = "submitRegistration"; private static final String ID_REGISTRATION_SUBMITED = "registrationInfo"; private static final String ID_FEEDBACK = "feedback"; private static final String ID_BACK = "back"; private static final String ID_WELCOME = "welcome"; private static final String ID_CAPTCHA = "captcha"; private static final String OPERATION_SAVE_USER = DOT_CLASS + "saveUser"; private static final String OPERATION_LOAD_USER = DOT_CLASS + "loadUser"; private static final String PARAM_USER_OID = "user"; private static final long serialVersionUID = 1L; private IModel<UserType> userModel; private boolean submited = false; String randomString = null; String captchaString = null; public PageSelfRegistration() { this(null); } public PageSelfRegistration(PageParameters pageParameters) { super(); final String userOid = getOidFromParams(pageParameters); userModel = new LoadableModel<UserType>(false) { private static final long serialVersionUID = 1L; @Override protected UserType load() { return createUserModel(userOid); } }; initLayout(); } private String getOidFromParams(PageParameters pageParameters) { if (pageParameters == null) { return null; } StringValue oidValue = pageParameters.get(PARAM_USER_OID); if (oidValue != null) { return oidValue.toString(); } return null; } private UserType createUserModel(final String userOid) { if (userOid != null) { PrismObject<UserType> result = runPrivileged(new Producer<PrismObject<UserType>>() { @Override public PrismObject<UserType> run() { LOGGER.trace("Loading preregistered user with oid {}.", userOid); Task task = createAnonymousTask(OPERATION_LOAD_USER); OperationResult result = new OperationResult(OPERATION_LOAD_USER); PrismObject<UserType> user = WebModelServiceUtils.loadObject(UserType.class, userOid, PageSelfRegistration.this, task, result); result.computeStatus(); return user; } }); if (result == null) { LOGGER.error("Failed to load preregistered user"); getSession().error( createStringResource("PageSelfRegistration.invalid.registration.link").getString()); throw new RestartResponseException(PageLogin.class); } return result.asObjectable(); } LOGGER.trace("Registration process for new user started"); return instantiateUser(); } private UserType instantiateUser() { PrismObjectDefinition<UserType> userDef = getUserDefinition(); PrismObject<UserType> user; try { user = userDef.instantiate(); } catch (SchemaException e) { UserType userType = new UserType(); user = userType.asPrismObject(); } return user.asObjectable(); } private PrismObjectDefinition<UserType> getUserDefinition() { return getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } private void initLayout() { Form<?> mainForm = new Form<>(ID_MAIN_FORM); initAccessBehaviour(mainForm); add(mainForm); MultiLineLabel welcome = new MultiLineLabel(ID_WELCOME, createStringResource("PageSelfRegistration.welcome.message")); welcome.setOutputMarkupId(true); mainForm.add(welcome); // feedback FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK, new ContainerFeedbackMessageFilter(PageSelfRegistration.this)); feedback.setOutputMarkupId(true); mainForm.add(feedback); TextPanel<String> firstName = new TextPanel<>(ID_FIRST_NAME, new PropertyModel<String>(userModel, UserType.F_GIVEN_NAME.getLocalPart() + ".orig") { private static final long serialVersionUID = 1L; @Override public void setObject(String object) { userModel.getObject().setGivenName(new PolyStringType(object)); } }); initInputProperties(feedback, firstName); mainForm.add(firstName); TextPanel<String> lastName = new TextPanel<>(ID_LAST_NAME, new PropertyModel<String>(userModel, UserType.F_FAMILY_NAME.getLocalPart() + ".orig") { private static final long serialVersionUID = 1L; @Override public void setObject(String object) { userModel.getObject().setFamilyName(new PolyStringType(object)); } }); initInputProperties(feedback, lastName); mainForm.add(lastName); TextPanel<String> email = new TextPanel<>(ID_EMAIL, new PropertyModel<String>(userModel, UserType.F_EMAIL_ADDRESS.getLocalPart())); initInputProperties(feedback, email); mainForm.add(email); ProtectedStringType initialPassword = null; PasswordPanel password = new PasswordPanel(ID_PASSWORD, Model.of(initialPassword)); password.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); password.getBaseFormComponent().setRequired(true); mainForm.add(password); CaptchaPanel captcha = new CaptchaPanel(ID_CAPTCHA); captcha.setOutputMarkupId(true); mainForm.add(captcha); AjaxSubmitButton register = new AjaxSubmitButton(ID_SUBMIT_REGISTRATION) { private static final long serialVersionUID = 1L; @Override protected void onError(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) { showErrors(target); } protected void onSubmit(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) { submitRegistration(target); } }; mainForm.add(register); MultiLineLabel label = new MultiLineLabel(ID_REGISTRATION_SUBMITED, createStringResource("PageSelfRegistration.registration.confirm.message")); add(label); label.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return submited; } @Override public boolean isEnabled() { return submited; } }); AjaxButton back = new AjaxButton(ID_BACK) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { setResponsePage(PageLogin.class); } }; mainForm.add(back); } private void initAccessBehaviour(Form mainForm) { mainForm.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return !submited; } @Override public boolean isEnabled() { return !submited; } }); } private void showErrors(AjaxRequestTarget target) { target.add(get(createComponentPath(ID_MAIN_FORM, ID_FEEDBACK))); target.add(getFeedbackPanel()); } private void initInputProperties(FeedbackPanel feedback, TextPanel<String> input) { input.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); input.getBaseFormComponent().setRequired(true); feedback.setFilter(new ContainerFeedbackMessageFilter(input.getBaseFormComponent())); input.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isEnabled() { return getOidFromParams(getPageParameters()) == null; } }); } private CaptchaPanel getCaptcha() { return (CaptchaPanel) get(createComponentPath(ID_MAIN_FORM, ID_CAPTCHA)); } private void submitRegistration(AjaxRequestTarget target) { if (!validateCaptcha(target)) { return; } OperationResult result = runPrivileged(new Producer<OperationResult>() { @Override public OperationResult run() { Task task = createAnonymousTask(OPERATION_SAVE_USER); task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); OperationResult result = new OperationResult(OPERATION_SAVE_USER); saveUser(task, result); result.computeStatus(); return result; } }); if (result.getStatus() == OperationResultStatus.SUCCESS) { submited = true; getSession() .success(createStringResource("PageSelfRegistration.registration.success").getString()); switch (getSelfRegistrationConfiguration().getAuthenticationMethod()) { case MAIL: target.add(PageSelfRegistration.this); break; case SMS: throw new UnsupportedOperationException(); case NONE: setResponsePage(PageLogin.class); } LOGGER.trace("Registration for user {} was successfull.", userModel.getObject()); } else { getSession().error( createStringResource("PageSelfRegistration.registration.error", result.getMessage()) .getString()); removePassword(target); updateCaptcha(target); target.add(getFeedbackPanel()); LOGGER.error("Failed to register user {}. Reason {}", userModel.getObject(), result.getMessage()); return; } target.add(getFeedbackPanel()); target.add(this); } private boolean validateCaptcha(AjaxRequestTarget target) { CaptchaPanel captcha = getCaptcha(); if (captcha.getRandomText() == null) { String message = createStringResource("PageSelfRegistration.captcha.validation.failed") .getString(); LOGGER.error(message); getSession().error(message); target.add(getFeedbackPanel()); updateCaptcha(target); return false; } if (captcha.getCaptchaText() != null && captcha.getRandomText() != null) { if (!captcha.getCaptchaText().equals(captcha.getRandomText())) { String message = createStringResource("PageSelfRegistration.captcha.validation.failed") .getString(); LOGGER.error(message); getSession().error(message); updateCaptcha(target); target.add(getFeedbackPanel()); return false; } } LOGGER.trace("CAPTCHA Validation OK"); return true; } private void updateCaptcha(AjaxRequestTarget target) { CaptchaPanel captcha = new CaptchaPanel(ID_CAPTCHA); captcha.setOutputMarkupId(true); Form form = (Form) get(ID_MAIN_FORM); form.addOrReplace(captcha); target.add(form); } private void saveUser(Task task, OperationResult result) { ObjectDelta<UserType> userDelta = prepareUserDelta(task, result); userDelta.setPrismContext(getPrismContext()); WebModelServiceUtils.save(userDelta, ModelExecuteOptions.createOverwrite(), result, task, PageSelfRegistration.this); result.computeStatus(); } private ObjectDelta<UserType> prepareUserDelta(Task task, OperationResult result) { if (getOidFromParams(getPageParameters()) == null) { LOGGER.trace("Preparing user ADD delta (new user registration)"); UserType userType = prepareUserToSave(task, result); ObjectDelta<UserType> userDelta = ObjectDelta.createAddDelta(userType.asPrismObject()); LOGGER.trace("Going to register user {}", userDelta); return userDelta; } else { LOGGER.trace("Preparing user MODIFY delta (preregistered user registration)"); ObjectDelta<UserType> delta = ObjectDelta.createEmptyModifyDelta(UserType.class, getOidFromParams(getPageParameters()), getPrismContext()); if (getSelfRegistrationConfiguration().getInitialLifecycleState() != null) { delta.addModificationReplaceProperty(UserType.F_LIFECYCLE_STATE, getSelfRegistrationConfiguration().getInitialLifecycleState()); } delta.addModificationReplaceProperty(SchemaConstants.PATH_PASSWORD_VALUE, createPassword().getValue()); delta.addModificationReplaceContainer(SchemaConstants.PATH_NONCE, createNonce(getSelfRegistrationConfiguration().getNoncePolicy(), task, result) .asPrismContainerValue()); LOGGER.trace("Going to register user with modifications {}", delta); return delta; } } private UserType prepareUserToSave(Task task, OperationResult result) { SelfRegistrationDto selfRegistrationConfiguration = getSelfRegistrationConfiguration(); UserType userType = userModel.getObject(); UserType userToSave = userType.clone(); if (selfRegistrationConfiguration.getRequiredLifecycleState() != null) { String userLifecycle = userToSave.getLifecycleState(); if (!selfRegistrationConfiguration.getRequiredLifecycleState().equals(userLifecycle)) { LOGGER.error( "Registration not allowed for a user {} -> Unsatisfied Configuration for required lifecycle, expected {} but was {}", new Object[] { userToSave.getEmailAddress() != null ? userToSave.getEmailAddress() : userToSave, selfRegistrationConfiguration.getRequiredLifecycleState(), userLifecycle }); getSession().error(createStringResource( "PageSelfRegistration.registration.failed.unsatisfied.registration.configuration") .getString()); throw new RestartResponseException(this); } } CredentialsType credentials = createCredentials(selfRegistrationConfiguration.getNoncePolicy(), task, result); userToSave.setCredentials(credentials); if (selfRegistrationConfiguration.getInitialLifecycleState() != null) { LOGGER.trace("Setting initial lifecycle state of registered user to {}", selfRegistrationConfiguration.getInitialLifecycleState()); userToSave.setLifecycleState(selfRegistrationConfiguration.getInitialLifecycleState()); } try { getPrismContext().adopt(userToSave); } catch (SchemaException e) { // nothing to do, try without it } return userToSave; } private CredentialsType createCredentials(NonceCredentialsPolicyType noncePolicy, Task task, OperationResult result) { NonceType nonceType = createNonce(noncePolicy, task, result); PasswordType password = createPassword(); CredentialsType credentials = new CredentialsType(); credentials.setNonce(nonceType); credentials.setPassword(password); return credentials; } private NonceType createNonce(NonceCredentialsPolicyType noncePolicy, Task task, OperationResult result) { ProtectedStringType nonceCredentials = new ProtectedStringType(); nonceCredentials.setClearValue(generateNonce(noncePolicy, task, result)); NonceType nonceType = new NonceType(); nonceType.setValue(nonceCredentials); return nonceType; } private PasswordType createPassword() { PasswordType password = new PasswordType(); ProtectedStringType protectedString = new ProtectedStringType(); protectedString.setClearValue(getPassword()); password.setValue(protectedString); return password; } private String generateNonce(NonceCredentialsPolicyType noncePolicy, Task task, OperationResult result) { ValuePolicyType policy = null; if (noncePolicy != null && noncePolicy.getValuePolicyRef() != null) { PrismObject<ValuePolicyType> valuePolicy = WebModelServiceUtils.loadObject(ValuePolicyType.class, noncePolicy.getValuePolicyRef().getOid(), PageSelfRegistration.this, task, result); policy = valuePolicy.asObjectable(); } return ValuePolicyGenerator.generate(policy != null ? policy.getStringPolicy() : null, 24, result); } private String getPassword() { PasswordPanel password = (PasswordPanel) get(createComponentPath(ID_MAIN_FORM, ID_PASSWORD)); return (String) password.getBaseFormComponent().getModel().getObject(); } private void removePassword(AjaxRequestTarget target) { PasswordPanel password = (PasswordPanel) get(createComponentPath(ID_MAIN_FORM, ID_PASSWORD)); for (FormComponent comp : password.getFormComponents()) { comp.getModel().setObject(null); } target.add(password); } @Override protected void createBreadcrumb() { // don't create breadcrumb for registration page } }
package com.koch.ambeth.service.merge.model; import com.koch.ambeth.util.collections.IList; /** * Allows to extract an {@link IObjRef} handle by directly casting a given entity instance to this * interface */ public interface IObjRefType { /** * Creates an {@link IObjRef} handle pointing to this entity via its primary identifier. If the * current entity is not yet persisted in its data repository the returned instance is an * {@link IDirectObjRef}. * * @return Handle pointing to this entity via the primary identifier */ IObjRef getObjRef(); /** * Creates an {@link IObjRef} handle pointing to this entity via its provided identifying member * name: That is either the primary identifier or any additional unique identifier. * * @param identifierMemberName The member name describing the expected identifier to be created * from * @return Handle pointing to this entity via the specified identifier */ IObjRef getObjRef(String identifierMemberName); /** * Creates a list of all valid (=non-null) identifiers pointing to this entity. If the entity does * not have any non-null unique identifiers and is also not yet persisted the returned collection * is empty. * * @return The list of all valid handles each based on a different identifier pointing to this * entity */ IList<IObjRef> getAllObjRefs(); }
package org.broadinstitute.sting.playground.gatk.walkers.indels; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMReadGroupRecord; import net.sf.samtools.SAMRecord; import org.broadinstitute.sting.gatk.refdata.RODIterator; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedData; import org.broadinstitute.sting.gatk.refdata.rodRefSeq; import org.broadinstitute.sting.gatk.walkers.ReadWalker; import org.broadinstitute.sting.playground.utils.CircularArray; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.GenomeLocParser; import org.broadinstitute.sting.utils.cmdLine.Argument; public class IndelGenotyperWalker extends ReadWalker<Integer,Integer> { @Argument(fullName="bed", shortName="bed", doc="BED output file name", required=true) public java.io.File bed_file; @Argument(fullName="somatic", shortName="somatic", doc="Perform somatic calls; two input alignment files must be specified", required=false) public boolean call_somatic = false; @Argument(fullName="verbose", shortName="verbose", doc="Tell us what you are calling now (printed to stdout)", required=false) public boolean verbose = false; @Argument(fullName="minCoverage", shortName="minCoverage", doc="must have minCoverage or more reads to call indel; with --somatic this value is applied to tumor sample", required=false) public int minCoverage = 6; @Argument(fullName="minNormalCoverage", shortName="minNormalCoverage", doc="used only with --somatic; normal sample must have at least minNormalCoverage or more reads to call germline/somatic indel", required=false) public int minNormalCoverage = 4; @Argument(fullName="minFraction", shortName="minFraction", doc="minimum fraction of reads with indels at a site, out of all reads covering the site, required for a call", required=false) public double minFraction = 0.3; @Argument(fullName="minConsensusFraction", shortName="minConsensusFraction", doc="Minimum fraction of reads with indel at the site that must contain consensus indel in order to make the call", required=false) public double minConsensusFraction = 0.7; @Argument(fullName="refseq", shortName="refseq", doc="Name of RefSeq transcript annotation file. If specified, indels will be annotated as GENOMIC/UTR/INTRON/CODING", required=false) public String RefseqFileName = null; private static int WINDOW_SIZE = 200; private RunningCoverage coverage; private RunningCoverage normal_coverage; // when performing somatic calls, we will be using this one for normal, and 'coverage' for tumor private int currentContigIndex = -1; private int currentPosition = -1; // position of the last read we've seen on the current contig private String refName = null; private java.io.Writer output = null; private GenomeLoc location = null; private RODIterator<rodRefSeq> refseqIterator=null; private Set<String> normal_samples = new HashSet<String>(); private Set<String> tumor_samples = new HashSet<String>(); private int MISMATCH_WIDTH = 5; // 5 bases on each side of the indel private int MISMATCH_CUTOFF = 1000000; private double AV_MISMATCHES_PER_READ = 1.5; private static String annGenomic = "GENOMIC"; private static String annIntron = "INTRON"; private static String annUTR = "UTR"; private static String annCoding = "CODING"; private static String annUnknown = "UNKNOWN"; private SAMRecord lastRead; // "/humgen/gsa-scr1/GATK_Data/refGene.sorted.txt" @Override public void initialize() { coverage = new RunningCoverage(0,WINDOW_SIZE); if ( RefseqFileName != null ) { ReferenceOrderedData<rodRefSeq> refseq = new ReferenceOrderedData<rodRefSeq>("refseq", new java.io.File(RefseqFileName),rodRefSeq.class); refseqIterator = refseq.iterator(); } int nSams = getToolkit().getArguments().samFiles.size(); location = GenomeLocParser.createGenomeLoc(0,1); if ( call_somatic ) { if ( nSams != 2 ) { System.out.println("In --somatic mode two input bam files must be specified (normal/tumor)"); System.exit(1); } normal_coverage = new RunningCoverage(0,WINDOW_SIZE); // this is an ugly hack: we want to be able to tell what file (tumor/normal sample) each read came from, // but reads do not carry this information! // SAMFileReader rn = new SAMFileReader(getToolkit().getArguments().samFiles.get(0)); // for ( SAMReadGroupRecord rec : rn.getFileHeader().getReadGroups() ) { // normal_samples.add(rec.getSample()); // rn.close(); // rn = new SAMFileReader(getToolkit().getArguments().samFiles.get(1)); // for ( SAMReadGroupRecord rec : rn.getFileHeader().getReadGroups() ) { // tumor_samples.add(rec.getSample()); // rn.close(); } else { if ( nSams != 1 ) System.out.println("WARNING: multiple input files specified. \n"+ "WARNING: Without --somatic option they will be merged and processed as a single sample"); } try { output = new java.io.FileWriter(bed_file); } catch (IOException e) { throw new StingException("Failed to open file for writing BED output"); } } void assignReadGroups(final SAMFileHeader mergedHeader) { Set<String> normal = new HashSet<String>(); // list normal samples here Set<String> tumor = new HashSet<String>(); // list tumor samples here SAMFileReader rn = new SAMFileReader(getToolkit().getArguments().samFiles.get(0)); for ( SAMReadGroupRecord rec : rn.getFileHeader().getReadGroups() ) { normal.add(new String(rec.getSample())); } rn.close(); rn = new SAMFileReader(getToolkit().getArguments().samFiles.get(1)); for ( SAMReadGroupRecord rec : rn.getFileHeader().getReadGroups() ) { tumor.add(new String(rec.getSample())); } rn.close(); // now we know what samples are normal, and what are tumor; let's assign dynamic read groups we get in merged header: for ( SAMReadGroupRecord mr : mergedHeader.getReadGroups() ) { if ( normal.contains(mr.getSample() ) ) { normal_samples.add( new String(mr.getReadGroupId()) ); System.out.println("Read group "+ mr.getReadGroupId() + "--> Sample "+ mr.getSample() + " (normal)"); } else if ( tumor.contains(mr.getSample() ) ) { tumor_samples.add( new String(mr.getReadGroupId()) ); System.out.println("Read group "+ mr.getReadGroupId() + "--> Sample "+ mr.getSample() + " (tumor)"); } else throw new StingException("Unrecognized sample "+mr.getSample() +" in merged SAM stream"); } System.out.println(); } @Override public Integer map(char[] ref, SAMRecord read) { if ( read.getReadUnmappedFlag() && read.getReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX && read.getAlignmentStart() == SAMRecord.NO_ALIGNMENT_START ) { System.out.println("I think I reached unmapped reads at the end of the file(s) and I am done..."); return -1; } // if ( read.getAlignmentStart() < 112337549 && read.getAlignmentEnd() > 112337550 ) { // System.out.print("adding "+read.getReadString()+" "+read.getCigarString()); if ( read.getReadUnmappedFlag() || read.getDuplicateReadFlag() || read.getNotPrimaryAlignmentFlag() || read.getMappingQuality() == 0 ) { // System.out.println(" ignored"); return 0; // we do not need those reads! } // System.out.print(" added"); if ( read.getReferenceIndex() != currentContigIndex ) { // we just jumped onto a new contig if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal throw new StingException("Read "+read.getReadName()+": contig is out of order"); if ( call_somatic) emit_somatic(1000000000, true); // print remaining indels from the previous contig (if any); else emit(1000000000,true); currentContigIndex = read.getReferenceIndex(); currentPosition = read.getAlignmentStart(); refName = new String(read.getReferenceName()); location.setContig(refName); coverage.clear(); // reset coverage window; this will also set reference position to 0 if ( call_somatic) normal_coverage.clear(); } if ( read.getAlignmentStart() < currentPosition ) throw new StingException("Read "+read.getReadName() +" out of order on the contig\n"+ "Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition +"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-" +lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString()); currentPosition = read.getAlignmentStart(); if ( read.getAlignmentStart() < coverage.getStart() ) { // should never happen throw new StingException("Read "+read.getReadName()+": out of order on the contig\n"+ "Read starts at "+read.getReferenceName()+":"+read.getAlignmentStart()+ " (cigar="+read.getCigarString()+ "); window starts at "+coverage.getStart()); } lastRead = read; // a little trick here: we want to make sure that current read completely fits into the current // window so that we can accumulate the coverage/indel counts over the whole length of the read. // The ::getAlignmentEnd() method returns the last position on the reference where bases from the // read actually match (M or D cigar elements). After our cleaning procedure, we can have reads that end // with I element, which is not gonna be counted into alignment length on the reference. On the other hand, // in this program we assign insertions, internally, to the first base *after* the insertion position. // Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds. long alignmentEnd = read.getAlignmentEnd(); Cigar c = read.getCigar(); if ( c.getCigarElement(c.numCigarElements()-1).getOperator() == CigarOperator.I) alignmentEnd++; if ( alignmentEnd > coverage.getStop()) { // we don't emit anything until we reach a read that does not fit into the current window. // At that point we shift the window to the start of that read and emit everything prior to // that position (reads are sorted, so we are not gonna see any more coverage at those lower positions). // Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting // the window to the read's start will ensure that the read fits... if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false ); else emit( read.getAlignmentStart(), false ); if ( read.getAlignmentEnd() > coverage.getStop()) { // ooops, looks like the read does not fit into the current window!! throw new StingException("Read "+read.getReadName()+": out of coverage window bounds.Probably window is too small.\n"+ "Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+ read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+"; window start="+coverage.getStart()+ "; window end="+coverage.getStop()); } } if ( call_somatic ) { // this is a hack. currently we can get access to the merged header only through the read, // so below we figure out which of the reassigned read groups in the merged stream are normal // and which are tumor, and we make sure we do it only once: if ( normal_samples.size() == 0 ) assignReadGroups(read.getHeader()); String rg = (String)read.getAttribute("RG"); if ( rg == null ) throw new StingException("Read "+read.getReadName()+" has no read group in merged stream"); if ( normal_samples.contains(rg) ) { // System.out.println(" TO NORMAL"); normal_coverage.add(read,ref); } else if ( tumor_samples.contains(rg) ) { // System.out.println(" TO TUMOR"); coverage.add(read,ref); } else { throw new StingException("Unrecognized read group in merged stream: "+rg); } } else { coverage.add(read, ref); } return 1; } /** Output indel calls up to the specified position and shift the coverage array(s): after this method is executed * first elements of the coverage arrays map onto 'position' * * @param position */ private void emit(long position, boolean force) { long stop_at = position; // we will shift to this position instead of passed 'position' // argument if we did not cover MISMATCH_WIDTH bases around the last indel yet for ( long pos = coverage.getStart() ; pos < Math.min(position,coverage.getStop()+1) ; pos++ ) { List<IndelVariant> variants = coverage.indelsAt(pos); if ( variants.size() == 0 ) continue; // no indels // if we are here, we got a variant int cov = coverage.coverageAt(pos); if ( cov < minCoverage ) continue; // low coverage long left = Math.max( pos-MISMATCH_WIDTH, coverage.getStart() ); long right = pos+MISMATCH_WIDTH; if ( right > coverage.getStop() ) { // we do not have enough bases in the current window // in order to assess mismatch rate if( force ) { // if we were asked to force-shift, then, well, shift anyway right = coverage.getStop() ; } else { // shift to the position prior to the last indel so that we could get all the mismatch counts around it later stop_at = left; break; } } // count mismatches around the current indel, inside specified window (MISMATCH_WIDTH on each side): int total_mismatches = 0; for ( long k = left; k <= right ; k++ ) total_mismatches+=coverage.mismatchesAt(k); if ( total_mismatches > MISMATCH_CUTOFF || total_mismatches > ((double)cov)*AV_MISMATCHES_PER_READ) { System.out.println(refName+"\t"+(pos-1)+"\t"+ "\tTOO DIRTY\t"+total_mismatches); continue; // too dirty } location.setStart(pos); location.setStop(pos); // retrieve annotation data rodRefSeq annotation = refseqIterator.seekForward(location); int total_variant_count = 0; int max_variant_count = 0; String indelString = null; int event_length = 0; // length of the event on the reference for ( IndelVariant var : variants ) { int cnt = var.getCount(); total_variant_count +=cnt; if ( cnt > max_variant_count ) { max_variant_count = cnt; indelString = var.getBases(); event_length = var.lengthOnRef(); } } if ( (double)total_variant_count > minFraction * cov && (double) max_variant_count > minConsensusFraction*total_variant_count ) { String annotationString = getAnnotationString(annotation); String message = refName+"\t"+(pos-1)+"\t"+(event_length > 0 ? pos-1+event_length : pos-1)+ "\t"+(event_length>0? "-":"+")+indelString +":"+total_variant_count+"/"+cov; try { output.write(message+"\n"); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); throw new StingException("Error encountered while writing into output BED file"); } if ( verbose ) System.out.println(message + "\t"+ annotationString); } // for ( IndelVariant var : variants ) { // System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount()); } coverage.shift((int)(stop_at - coverage.getStart() ) ); } /** Output somatic indel calls up to the specified position and shift the coverage array(s): after this method is executed * first elements of the coverage arrays map onto 'position' * * @param position */ private void emit_somatic(long position, boolean force) { long stop_at = position; for ( long pos = coverage.getStart() ; pos < Math.min(position,coverage.getStop()+1) ; pos++ ) { List<IndelVariant> tumor_variants = coverage.indelsAt(pos); List<IndelVariant> normal_variants = normal_coverage.indelsAt(pos); if ( tumor_variants.size() == 0 ) continue; // no indels in tumor int tumor_cov = coverage.coverageAt(pos); int normal_cov = normal_coverage.coverageAt(pos); if ( tumor_cov < minCoverage ) continue; // low coverage if ( normal_cov < minNormalCoverage ) continue; // low coverage long left = Math.max( pos-MISMATCH_WIDTH, coverage.getStart() ); long right = pos+MISMATCH_WIDTH; if ( right > coverage.getStop() ) { // we do not have enough bases in the current window // in order to assess mismatch rate if( force ) { // if we were asked to force-shift, then, well, shift anyway right = coverage.getStop() ; } else { // shift to the position prior to the last indel so that we could get all the mismatch counts around it later stop_at = left; break; } } // count mismatches around the current indel, inside specified window (MISMATCH_WIDTH on each side): int total_mismatches_normal = 0; int total_mismatches_tumor = 0; for ( long k = left; k <= right ; k++ ) { total_mismatches_tumor+=coverage.mismatchesAt(k); total_mismatches_normal+=normal_coverage.mismatchesAt(k); } if ( total_mismatches_normal > MISMATCH_CUTOFF || total_mismatches_normal > ((double)normal_cov)*AV_MISMATCHES_PER_READ) { System.out.println(refName+"\t"+(pos-1)+"\t"+ "\tNORMAL TOO DIRTY\t"+total_mismatches_normal); continue; // too dirty } if ( total_mismatches_tumor > MISMATCH_CUTOFF || total_mismatches_tumor > ((double)tumor_cov)*AV_MISMATCHES_PER_READ) { System.out.println(refName+"\t"+(pos-1)+"\t"+ "\tTUMOR TOO DIRTY\t"+total_mismatches_tumor); continue; // too dirty } location.setStart(pos); location.setStop(pos); // retrieve annotation data rodRefSeq annotation = refseqIterator.seekForward(location); int total_variant_count_tumor = 0; int max_variant_count_tumor = 0; String indelStringTumor = null; int event_length_tumor = 0; // length of the event on the reference for ( IndelVariant var : tumor_variants ) { int cnt = var.getCount(); total_variant_count_tumor +=cnt; if ( cnt > max_variant_count_tumor ) { max_variant_count_tumor = cnt; indelStringTumor = var.getBases(); event_length_tumor = var.lengthOnRef(); } } if ( (double)total_variant_count_tumor > minFraction * tumor_cov && (double) max_variant_count_tumor > minConsensusFraction*total_variant_count_tumor ) { String annotationString = getAnnotationString(annotation); long leftpos = pos; long rightpos = pos+event_length_tumor-1; if ( event_length_tumor == 0 ) { // insertion leftpos rightpos = leftpos; } String message = refName+"\t"+leftpos+"\t"+rightpos+ "\t"+(event_length_tumor >0? "-":"+")+indelStringTumor +":"+total_variant_count_tumor+"/"+tumor_cov; if ( normal_variants.size() == 0 ) { try { output.write(message+"\n"); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); throw new StingException("Error encountered while writing into output BED file"); } message += "\tSOMATIC\t"; } else { message += "\tGERMLINE\t"; } message += annotationString; if ( verbose ) System.out.println(message); } // for ( IndelVariant var : variants ) { // System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount()); } coverage.shift((int)(stop_at - coverage.getStart() ) ); normal_coverage.shift((int)(stop_at - normal_coverage.getStart() ) ); } private String getAnnotationString(rodRefSeq ann) { if ( ann == null ) return annGenomic; else { if ( ann.isExon() ) { if ( ann.isCoding() ) return annCoding; else return annUTR; } else { if ( ann.isCoding() ) return annIntron; else return annUnknown; } } } @Override public void onTraversalDone(Integer result) { if ( call_somatic ) emit_somatic(1000000000, true); else emit(1000000000,true); // emit everything we might have left try { output.close(); } catch (IOException e) { System.out.println("Failed to close output BED file gracefully, data may be lost"); e.printStackTrace(); } super.onTraversalDone(result); } @Override public Integer reduce(Integer value, Integer sum) { if ( value == -1 ) { onTraversalDone(sum); System.exit(1); } sum += value; return sum; } @Override public Integer reduceInit() { return new Integer(0); } static class IndelVariant { public static enum Type { I, D}; private String bases; private Type type; private int count; public IndelVariant(Type type, String bases) { this.type = type; this.bases = bases; this.count = 1; } public void increment(int i) { count += i; } /** Returns length of the event on the reference (number of deleted bases * for deletions, -1 for insertions. * @return */ public int lengthOnRef() { if ( type == Type.D ) return bases.length(); else return 0; } public void increment() { count+=1; } public int getCount() { return count; } public String getBases() { return bases; } public Type getType() { return type; } @Override public boolean equals(Object o) { if ( ! ( o instanceof IndelVariant ) ) return false; IndelVariant that = (IndelVariant)o; return ( this.type == that.type && this.bases.equals(that.bases) ); } public boolean equals(Type type, String bases) { return ( this.type == type && this.bases.equals(bases) ); } } static class RunningCoverage { private long start; // we keep coverage starting at this position on the reference private CircularArray.Int coverageWindow; private CircularArray< List< IndelVariant > > indels; private CircularArray.Int mismatches; private static List<IndelVariant> emptyIndelList; static { emptyIndelList = new ArrayList<IndelVariant>(); } public RunningCoverage(long start, int length) { this.start = start; coverageWindow = new CircularArray.Int(length); indels = new CircularArray< List<IndelVariant> >(length); mismatches = new CircularArray.Int(length); } /** Returns 1-based reference start position of the interval this object keeps coverage for. * * @return */ public long getStart() { return start; } /** Returns 1-based reference stop position (inclusive) of the interval this object keeps coverage for. * * @return */ public long getStop() { return start + coverageWindow.length() - 1; } /** Returns the number of reads spanning over the specified reference position * (regardless of whether they have a base or indel at that specific location) * @param refPos position on the reference; must be within the bounds of the window, * otherwise IndexOutOfBoundsException will be thrown */ public int coverageAt(final long refPos) { return coverageWindow.get( (int)( refPos - start ) ); } public int mismatchesAt(final long refPos) { return mismatches.get((int)(refPos-start)); } public List<IndelVariant> indelsAt( final long refPos ) { List<IndelVariant> l = indels.get((int)( refPos - start )); if ( l == null ) return emptyIndelList; else return l; } /** Increments coverage in the currently held window for every position covered by the * specified read; we count the hole span of read getAlignmentStart()-getAlignmentEnd() here, * regardless of whether there are indels in the middle.Read must be completely within the current * window, or an exception will be thrown. * @param r */ public void add(SAMRecord r, char [] ref) { final long rStart = r.getAlignmentStart(); final long rStop = r.getAlignmentEnd(); final String readBases = r.getReadString().toUpperCase(); int localStart = (int)( rStart - start ); // start of the alignment wrt start of the current window try { for ( int k = localStart; k <= (int)(rStop-start) ; k++ ) coverageWindow.increment(k, 1); } catch ( IndexOutOfBoundsException e) { // replace the message and re-throw: throw new IndexOutOfBoundsException("Current coverage window: "+getStart()+"-"+getStop()+ "; illegal attempt to add read spanning "+rStart+"-"+rStop); } // now let's extract indels: Cigar c = r.getCigar(); final int nCigarElems = c.numCigarElements(); // if read has no indels, there is nothing to do if ( c.numCigarElements() <= 1 ) return ; int posOnRead = 0; int posOnRef = 0; // the chunk of reference ref[] that we have access to is aligned with the read: // its start on the actual full reference contig is r.getAlignmentStart() // int mm=0; for ( int i = 0 ; i < nCigarElems ; i++ ) { final CigarElement ce = c.getCigarElement(i); IndelVariant.Type type = null; String bases = null; int eventPosition = posOnRef; switch(ce.getOperator()) { case I: type = IndelVariant.Type.I; bases = readBases.substring(posOnRead,posOnRead+ce.getLength()); // will increment position on the read below, there's no 'break' statement yet... case H: case S: // here we also skip hard and soft-clipped bases on the read; according to SAM format specification, // alignment start position on the reference points to where the actually aligned // (not clipped) bases go, so we do not need to increment reference position here posOnRead += ce.getLength(); break; case D: type = IndelVariant.Type.D; bases = new String( ref, posOnRef, ce.getLength() ); posOnRef += ce.getLength(); break; case M: for ( int k = 0; k < ce.getLength(); k++, posOnRef++, posOnRead++ ) { if ( readBases.charAt(posOnRead) != Character.toUpperCase(ref[posOnRef]) ) { // mismatch! mismatches.increment(localStart+posOnRef, 1); } } break; // advance along the gapless block in the alignment default : throw new IllegalArgumentException("Unexpected operator in cigar string: "+ce.getOperator()); } if ( type == null ) continue; // element was not an indel, go grab next element... // we got an indel if we are here... if ( i == 0 ) logger.warn("Indel at the start of the read "+r.getReadName()); if ( i == nCigarElems - 1) logger.warn("Indel at the end of the read "+r.getReadName()); try { // note that here we will be assigning indels to the first deleted base or to the first // base after insertion, not to the last base before the event! updateCount(localStart+eventPosition, type, bases); } catch (IndexOutOfBoundsException e) { System.out.println("Read "+r.getReadName()+": out of coverage window bounds.Probably window is too small.\n"+ "Read length="+r.getReadLength()+"; cigar="+r.getCigarString()+"; start="+ r.getAlignmentStart()+"; end="+r.getAlignmentEnd()+"; window start="+getStart()+ "; window end="+getStop()); throw e; } } // System.out.println(r.getReadName()+"\t"+(r.getReadNegativeStrandFlag()?"RC":"FW")+"\t"+r.getCigarString()+"\t"+mm); // System.out.println(AlignmentUtils.alignmentToString(r.getCigar(), readBases, new String(ref), 0)); } /** Convenience shortcut method. Checks if indel of specified type and with specified bases is already recorded * for position <code>pos</code> (relative to start of the window getStart()). If such indel is found, the counter * is increased; if it is not found, a new indel (with count = 1, obviously) will be added at that position. If indel array * still had null at the specified position, this method will instantiate new list of indels for this position * transparently. * * @param pos * @param type * @param bases */ private void updateCount(int pos, IndelVariant.Type type, String bases) { List<IndelVariant> indelsAtSite = indels.get(pos); if ( indelsAtSite == null ) { indelsAtSite = new ArrayList<IndelVariant>(); indels.set(pos, indelsAtSite); } boolean found = false; for ( IndelVariant v : indelsAtSite ) { if ( ! v.equals(type, bases) ) continue; v.increment(); found = true; break; } if ( ! found ) indelsAtSite.add(new IndelVariant(type, bases)); } /** Resets reference start position to 0 and sets all coverage counts in the window to 0. * */ public void clear() { start = 0; coverageWindow.clear(); indels.clear(); } /** Shifts current window to the right along the reference contig by the specified number of bases. * Coverage counts computed earlier for the positions that remain in scope will be preserved. * @param offset */ public void shift(int offset) { start += offset; coverageWindow.shiftData(offset); indels.shiftData(offset); mismatches.shiftData(offset); } } }
package org.languagetool.rules.spelling.hunspell; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.apache.commons.lang3.StringUtils; import org.languagetool.*; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Categories; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.rules.spelling.suggestions.SuggestionsChanges; import org.languagetool.rules.spelling.suggestions.SuggestionsOrderer; import org.languagetool.rules.spelling.suggestions.SuggestionsOrdererFeatureExtractor; import org.languagetool.rules.spelling.suggestions.XGBoostSuggestionsOrderer; import org.languagetool.tools.Tools; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Pattern; import java.util.stream.Collectors; public class HunspellRule extends SpellingCheckRule { public static final String RULE_ID = "HUNSPELL_RULE"; protected static final String FILE_EXTENSION = ".dic"; protected final SuggestionsOrderer suggestionsOrderer; protected boolean needsInit = true; protected Hunspell.Dictionary hunspellDict = null; private static final ConcurrentLinkedQueue<String> activeChecks = new ConcurrentLinkedQueue<>(); private static final String NON_ALPHABETIC = "[^\\p{L}]"; private final boolean monitorRules; private final boolean runningExperiment; public static Queue<String> getActiveChecks() { return activeChecks; } private static final String[] WHITESPACE_ARRAY = new String[20]; static { for (int i = 0; i < 20; i++) { WHITESPACE_ARRAY[i] = StringUtils.repeat(' ', i); } } protected Pattern nonWordPattern; private final UserConfig userConfig; public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig) { this(messages, language, userConfig, Collections.emptyList()); } /** * @since 4.3 */ public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) { this(messages, language, userConfig, altLanguages, null); } public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel) { super(messages, language, userConfig, altLanguages, languageModel); super.setCategory(Categories.TYPOS.getCategory(messages)); this.userConfig = userConfig; this.monitorRules = System.getProperty("monitorActiveRules") != null; if (SuggestionsChanges.isRunningExperiment("NewSuggestionsOrderer")) { suggestionsOrderer = new SuggestionsOrdererFeatureExtractor(language, this.languageModel); runningExperiment = true; } else { suggestionsOrderer = new XGBoostSuggestionsOrderer(language, languageModel); runningExperiment = false; } } @Override public String getId() { return RULE_ID; } @Override public String getDescription() { return messages.getString("desc_spelling"); } protected boolean isQuotedCompound (AnalyzedSentence analyzedSentence, int idx, String token) { return false; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { List<RuleMatch> ruleMatches = new ArrayList<>(); if (needsInit) { init(); } if (hunspellDict == null) { // some languages might not have a dictionary, be silent about it return toRuleMatchArray(ruleMatches); } String monitoringText = this.getClass().getName() + ":" + this.getId() + ":" + sentence.getText(); try { if (monitorRules) { activeChecks.add(monitoringText); } String[] tokens = tokenizeText(getSentenceTextWithoutUrlsAndImmunizedTokens(sentence)); // starting with the first token to skip the zero-length START_SENT int len; if (sentence.getTokens().length > 1) { // if fixes exception in SuggestionsChangesTest len = sentence.getTokens()[1].getStartPos(); } else { len = sentence.getTokens()[0].getStartPos(); } for (int i = 0; i < tokens.length; i++) { String word = tokens[i]; if ((ignoreWord(Arrays.asList(tokens), i) || ignoreWord(word)) && !isProhibited(removeTrailingDot(word))) { len += word.length() + 1; continue; } if (isMisspelled(word)) { String cleanWord = word; if (word.endsWith(".")) { cleanWord = word.substring(0, word.length()-1); } RuleMatch ruleMatch = new RuleMatch(this, sentence, len, len + cleanWord.length(), messages.getString("spelling"), messages.getString("desc_spelling_short")); ruleMatch.setType(RuleMatch.Type.UnknownWord); if (userConfig == null || userConfig.getMaxSpellingSuggestions() == 0 || ruleMatches.size() <= userConfig.getMaxSpellingSuggestions()) { List<String> suggestions = getSuggestions(cleanWord); if (word.endsWith(".")) { int pos = 1; for (String suggestion : getSuggestions(word)) { if (!suggestions.contains(suggestion)) { suggestions.add(Math.min(pos, suggestions.size()), suggestion.substring(0, suggestion.length()-1)); pos += 2; // we mix the lists, as we don't know which one is the better one } } } List<String> additionalTopSuggestions = getAdditionalTopSuggestions(suggestions, cleanWord); if (additionalTopSuggestions.isEmpty() && word.endsWith(".")) { additionalTopSuggestions = getAdditionalTopSuggestions(suggestions, word). stream().map(k -> k + ".").collect(Collectors.toList()); } Collections.reverse(additionalTopSuggestions); for (String additionalTopSuggestion : additionalTopSuggestions) { if (!cleanWord.equals(additionalTopSuggestion)) { suggestions.add(0, additionalTopSuggestion); } } List<String> additionalSuggestions = getAdditionalSuggestions(suggestions, cleanWord); for (String additionalSuggestion : additionalSuggestions) { if (!cleanWord.equals(additionalSuggestion)) { suggestions.addAll(additionalSuggestions); } } Language acceptingLanguage = acceptedInAlternativeLanguage(cleanWord); boolean isSpecialCase = cleanWord.matches(".+-[A-ZÖÄÜ].*"); if (acceptingLanguage != null && !isSpecialCase) { if (isAcceptedWordFromLanguage(acceptingLanguage, cleanWord)) { break; } // e.g. "Der Typ ist in UK echt famous" -> could be German 'famos' ruleMatch = new RuleMatch(this, sentence, len, len + cleanWord.length(), Tools.i18n(messages, "accepted_in_alt_language", cleanWord, messages.getString(acceptingLanguage.getShortCode()))); ruleMatch.setType(RuleMatch.Type.Hint); } filterSuggestions(suggestions); filterDupes(suggestions); // TODO user suggestions // use suggestionsOrderer only w/ A/B - Testing or manually enabled experiments if (runningExperiment) { addSuggestionsToRuleMatch(cleanWord, Collections.emptyList(), suggestions, suggestionsOrderer, ruleMatch); } else if (userConfig != null && userConfig.getAbTest() != null && userConfig.getAbTest().equals("SuggestionsRanker") && suggestionsOrderer.isMlAvailable() && userConfig.getTextSessionId() != null) { boolean testingA = userConfig.getTextSessionId() % 2 == 0; if (testingA) { addSuggestionsToRuleMatch(cleanWord, Collections.emptyList(), suggestions, null, ruleMatch); } else { addSuggestionsToRuleMatch(cleanWord, Collections.emptyList(), suggestions, suggestionsOrderer, ruleMatch); } } else { addSuggestionsToRuleMatch(cleanWord, Collections.emptyList(), suggestions, null, ruleMatch); } } else { // limited to save CPU ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors")); } ruleMatches.add(ruleMatch); } len += word.length() + 1; } } finally { if (monitorRules) { activeChecks.remove(monitoringText); } } return toRuleMatchArray(ruleMatches); } /** * @since public since 4.1 */ @Experimental public boolean isMisspelled(String word) { try { if (needsInit) { init(); } boolean isAlphabetic = true; if (word.length() == 1) { // hunspell dictionaries usually do not contain punctuation isAlphabetic = Character.isAlphabetic(word.charAt(0)); } return (isAlphabetic && !"--".equals(word) && hunspellDict.misspelled(word) && !ignoreWord(word)) || isProhibited(removeTrailingDot(word)); } catch (IOException e) { throw new RuntimeException(e); } } private String removeTrailingDot(String word) { return StringUtils.removeEnd(word, "."); } public List<String> getSuggestions(String word) throws IOException { if (needsInit) { init(); } return hunspellDict.suggest(word); } protected List<String> sortSuggestionByQuality(String misspelling, List<String> suggestions) { return suggestions; } protected String[] tokenizeText(String sentence) { return nonWordPattern.split(sentence); } protected String getSentenceTextWithoutUrlsAndImmunizedTokens(AnalyzedSentence sentence) { StringBuilder sb = new StringBuilder(); AnalyzedTokenReadings[] sentenceTokens = getSentenceWithImmunization(sentence).getTokens(); for (int i = 1; i < sentenceTokens.length; i++) { String token = sentenceTokens[i].getToken(); if (sentenceTokens[i].isImmunized() || sentenceTokens[i].isIgnoredBySpeller() || isUrl(token) || isEMail(token) || isQuotedCompound(sentence, i, token)) { if (isQuotedCompound(sentence, i, token)) { sb.append(" ").append(token.substring(1)); } // replace URLs and immunized tokens with whitespace to ignore them for spell checking: else if (token.length() < 20) { sb.append(WHITESPACE_ARRAY[token.length()]); } else { for (int j = 0; j < token.length(); j++) { sb.append(' '); } } } else if (token.length() > 1 && token.codePointCount(0, token.length()) != token.length()) { // some symbols such as emojis () have a string length that equals 2 for (int charIndex = 0; charIndex < token.length();) { int unicodeCodePoint = token.codePointAt(charIndex); int increment = Character.charCount(unicodeCodePoint); if (increment == 1) { sb.append(token.charAt(charIndex)); } else { sb.append(" "); } charIndex += increment; } } else { sb.append(token); } } return sb.toString(); } @Override protected void init() throws IOException { super.init(); String langCountry = language.getShortCode(); if (language.getCountries().length > 0) { langCountry += "_" + language.getCountries()[0]; } String shortDicPath = "/" + language.getShortCode() + "/hunspell/" + langCountry + FILE_EXTENSION; String wordChars = ""; // set dictionary only if there are dictionary files: if (JLanguageTool.getDataBroker().resourceExists(shortDicPath)) { String path = getDictionaryPath(langCountry, shortDicPath); if ("".equals(path)) { hunspellDict = null; } else { hunspellDict = Hunspell.getInstance().getDictionary(path); if (!hunspellDict.getWordChars().isEmpty()) { wordChars = "(?![" + hunspellDict.getWordChars().replace("-", "\\-") + "])"; } addIgnoreWords(); } } nonWordPattern = Pattern.compile(wordChars + NON_ALPHABETIC); needsInit = false; } private void addIgnoreWords() throws IOException { hunspellDict.addWord(SpellingCheckRule.LANGUAGETOOL); hunspellDict.addWord(SpellingCheckRule.LANGUAGETOOLER); URL ignoreUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(getIgnoreFileName()); List<String> ignoreLines = Resources.readLines(ignoreUrl, Charsets.UTF_8); for (String ignoreLine : ignoreLines) { if (!ignoreLine.startsWith(" hunspellDict.addWord(ignoreLine); } } } private String getDictionaryPath(String dicName, String originalPath) throws IOException { URL dictURL = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(originalPath); String dictionaryPath; //in the webstart, java EE or OSGi bundle version, we need to copy the files outside the jar //to the local temporary directory if (StringUtils.equalsAny(dictURL.getProtocol(), "jar", "vfs", "bundle", "bundleresource")) { File tempDir = new File(System.getProperty("java.io.tmpdir")); File tempDicFile = new File(tempDir, dicName + FILE_EXTENSION); JLanguageTool.addTemporaryFile(tempDicFile); try (InputStream dicStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath)) { fileCopy(dicStream, tempDicFile); } File tempAffFile = new File(tempDir, dicName + ".aff"); JLanguageTool.addTemporaryFile(tempAffFile); if (originalPath.endsWith(FILE_EXTENSION)) { originalPath = originalPath.substring(0, originalPath.length() - FILE_EXTENSION.length()) + ".aff"; } try (InputStream affStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath)) { fileCopy(affStream, tempAffFile); } dictionaryPath = tempDir.getAbsolutePath() + "/" + dicName; } else { int suffixLength = FILE_EXTENSION.length(); try { dictionaryPath = new File(dictURL.toURI()).getAbsolutePath(); dictionaryPath = dictionaryPath.substring(0, dictionaryPath.length() - suffixLength); } catch (URISyntaxException e) { return ""; } } return dictionaryPath; } private void fileCopy(InputStream in, File targetFile) throws IOException { try (OutputStream out = new FileOutputStream(targetFile)) { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); } } /** * Used in combination with <code>acceptedInAlternativeLanguage</code> to surpress spelling * errors for words from a foreign language * @since 4.6 * @return true if the {@code word} from {@code language} can be considered as correctly spelled */ protected boolean isAcceptedWordFromLanguage(Language language, String word) { return false; } }
package org.languagetool.rules.spelling.hunspell; import com.google.common.io.Resources; import com.vdurmont.emoji.EmojiParser; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.languagetool.*; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.noop.NoopLanguage; import org.languagetool.rules.Categories; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.spelling.RuleWithLanguage; import org.languagetool.rules.spelling.SpellingCheckRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Pattern; import java.util.stream.Collectors; public class HunspellRule extends SpellingCheckRule { public static final String RULE_ID = "HUNSPELL_RULE"; protected static final String FILE_EXTENSION = ".dic"; private volatile boolean needsInit = true; protected volatile Hunspell hunspell = null; private static final Logger logger = LoggerFactory.getLogger(HunspellRule.class); private static final ConcurrentLinkedQueue<String> activeChecks = new ConcurrentLinkedQueue<>(); private static final String NON_ALPHABETIC = "[^\\p{L}]"; private static final boolean monitorRules = System.getProperty("monitorActiveRules") != null; //300 most common Portuguese words. They are used to avoid wrong split suggestions private final List<String> commonPortugueseWords = Arrays.asList("de", "e", "a", "o", "da", "do", "em", "que", "uma", "um", "com", "no", "se", "na", "para", "por", "os", "foi", "como", "dos", "as", "ao", "mais", "sua", "das", "não", "ou", "km", "seu", "pela", "ser", "pelo", "são", "também", "anos", "cidade", "entre", "era", "tem", "mas", "habitantes", "nos", "seus", "área", "até", "ele", "onde", "foram", "população", "região", "sobre", "nas", "nome", "parte", "quando", "ano", "aos", "grande", "mesmo", "pode", "primeiro", "segundo", "sendo", "suas", "ainda", "dois", "estado", "está", "família", "já", "muito", "outros", "americano", "depois", "durante", "maior", "primeira", "forma", "apenas", "banda", "densidade", "dia", "então", "município", "norte", "tempo", "após", "duas", "num", "pelos", "qual", "século", "ter", "todos", "três", "vez", "água", "acordo", "cobertos", "comuna", "contra", "ela", "grupo", "principal", "quais", "sem", "tendo", "às", "álbum", "alguns", "assim", "asteróide", "bem", "brasileiro", "cerca", "desde", "este", "localizada", "mundo", "outras", "período", "seguinte", "sido", "vida", "através", "cada", "conhecido", "final", "história", "partir", "país", "pessoas", "sistema", "terra", "teve", "tinha", "época", "administrativa", "censo", "departamento", "dias", "esta", "filme", "francesa", "música", "província", "série", "vezes", "além", "antes", "eles", "eram", "espécie", "governo", "podem", "vários", "censos", "distrito", "estão", "exemplo", "hoje", "início", "jogo", "lhe", "lugar", "muitos", "média", "novo", "numa", "número", "pois", "possui", "sob", "só", "todo", "tornou", "trabalho", "algumas", "devido", "estava", "fez", "filho", "fim", "grandes", "há", "isso", "lado", "local", "morte", "orbital", "outro", "passou", "países", "quatro", "representa", "seja", "sempre", "sul", "várias", "capital", "chamado", "começou", " enquanto", "fazer", "lançado", "meio", "nova", "nível", "pelas", "poder", "presidente", "redor", "rio", "tarde", "todas", "carreira", "casa", "década", "estimada", "guerra", "havia", "livro", "localidades", "maioria", "muitas", "obra", "origem", "pai", "pouco", "principais", "produção", "programa", "qualquer", "raio", "seguintes", "sucesso", "título", "aproximadamente", "caso", "centro", "conhecida", "construção", "desta", "diagrama", "faz", "ilha", "importante", "mar", "melhor", "menos", "mesma", "metros", "mil", "nacional", "populacional", "quase", "rei", "sede", "segunda", "tipo", "toda", "uso", "velocidade", "vizinhança", "volta", "base", "brasileira", "clube", "desenvolvimento", "deste", "diferentes", "diversos", "empresa", "entanto", "futebol", "geral", "junto", "longo", "obras", "outra", "pertencente", "política", "português", "principalmente", "processo", "quem", "seria", "têm", "versão", "TV", "acima", "atual", "bairro", "chamada", "cinco", "conta", "corpo", "dentro", "deve"); public static Queue<String> getActiveChecks() { return activeChecks; } private static final String[] WHITESPACE_ARRAY = new String[20]; static { for (int i = 0; i < 20; i++) { WHITESPACE_ARRAY[i] = StringUtils.repeat(' ', i); } } protected Pattern nonWordPattern; private final UserConfig userConfig; private final List<RuleWithLanguage> enSpellRules; public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig) { this(messages, language, userConfig, Collections.emptyList()); } /** * @since 4.3 */ public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) { this(messages, language, userConfig, altLanguages, null); } public HunspellRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel) { super(messages, language, userConfig, altLanguages, languageModel); super.setCategory(Categories.TYPOS.getCategory(messages)); this.userConfig = userConfig; enSpellRules = getEnglishSpellingRules(); } private List<RuleWithLanguage> getEnglishSpellingRules() { List<RuleWithLanguage> spellingRules = new ArrayList<>(); Language en; try { en = Languages.getLanguageForShortCode("en-US"); } catch (IllegalArgumentException e) { logger.warn("Could not create en-US language for spell-check fallback, multi-lingual spell checking is not available"); return spellingRules; } List<Rule> rules; try { rules = new ArrayList<>(en.getRelevantRules(messages, userConfig, null, Collections.emptyList())); rules.addAll(en.getRelevantLanguageModelCapableRules(messages, null, null, userConfig, null, Collections.emptyList())); } catch (IOException e) { throw new RuntimeException(e); } for (Rule rule : rules) { if (rule.isDictionaryBasedSpellingRule()) { spellingRules.add(new RuleWithLanguage(rule, en)); } } return spellingRules; } @Override public String getId() { return RULE_ID; } @Override public String getDescription() { return messages.getString("desc_spelling"); } protected boolean isQuotedCompound (AnalyzedSentence analyzedSentence, int idx, String token) { return false; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { List<RuleMatch> ruleMatches = new ArrayList<>(); ensureInitialized(); if (hunspell == null) { // some languages might not have a dictionary, be silent about it return toRuleMatchArray(ruleMatches); } long sentLength = Arrays.stream(sentence.getTokensWithoutWhitespace()).filter(k -> !k.isNonWord()).count() - 1; // -1 for the SENT_START token String monitoringText = getClass().getName() + ":" + getId() + ":" + sentence.getText(); try { if (monitorRules) { activeChecks.add(monitoringText); } String[] tokens = tokenizeText(getSentenceTextWithoutUrlsAndImmunizedTokens(sentence)); // starting with the first token to skip the zero-length START_SENT int len; if (sentence.getTokens().length > 1) { // if fixes exception in SuggestionsChangesTest len = sentence.getTokens()[1].getStartPos(); } else { len = sentence.getTokens()[0].getStartPos(); } int prevStartPos = -1; int misspelledButEnglish = 0; for (int i = 0; i < tokens.length; i++) { String word = tokens[i]; if ((ignoreWord(Arrays.asList(tokens), i) || ignoreWord(word)) && !isProhibited(cutOffDot(word))) { prevStartPos = len; len += word.length() + 1; continue; } if (isMisspelled(word)) { if (isEnglish(word)) { misspelledButEnglish++; } String cleanWord = word.endsWith(".") ? word.substring(0, word.length() - 1) : word; if (i > 0 && prevStartPos != -1) { String prevWord = tokens[i-1]; boolean ignoreSplitting = false; if (this.language.getShortCode().equals("pt") && commonPortugueseWords.contains(prevWord.toLowerCase())) { ignoreSplitting = true; } if (!ignoreSplitting && prevWord.length() > 0) { // "thanky ou" -> "thank you" String sugg1a = prevWord.substring(0, prevWord.length()-1); String sugg1b = cutOffDot(prevWord.substring(prevWord.length()-1) + word); if (!isMisspelled(sugg1a) && !isMisspelled(sugg1b)) { RuleMatch rm = createWrongSplitMatch(sentence, ruleMatches, len, cleanWord, sugg1a, sugg1b, prevStartPos); if (rm != null) { ruleMatches.add(rm); } } // "than kyou" -> "thank you" String sugg2a = prevWord + word.charAt(0); String sugg2b = cutOffDot(word.substring(1)); if (!isMisspelled(sugg2a) && !isMisspelled(sugg2b)) { RuleMatch rm = createWrongSplitMatch(sentence, ruleMatches, len, cleanWord, sugg2a, sugg2b, prevStartPos); if (rm != null) { ruleMatches.add(rm); } } } } RuleMatch ruleMatch = new RuleMatch(this, sentence, len, len + cleanWord.length(), messages.getString("spelling"), messages.getString("desc_spelling_short")); ruleMatch.setType(RuleMatch.Type.UnknownWord); if (userConfig == null || userConfig.getMaxSpellingSuggestions() == 0 || ruleMatches.size() <= userConfig.getMaxSpellingSuggestions()) { ruleMatch.setLazySuggestedReplacements(() -> { try { return calcSuggestions(word, cleanWord); } catch (IOException e) { throw new RuntimeException(e); } }); } else { // limited to save CPU ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors")); } ruleMatches.add(ruleMatch); if (sentLength > 3) { float enRatio = (float)misspelledButEnglish / sentLength; //System.out.println("ER en??: " + enRatio + ": " + misspelledButEnglish + " / " + sentLength + " - " + sentence.getText()); if (enRatio > 0.66) { //System.out.println("ER en!!: " + enRatio + ": " + misspelledButEnglish + " / " + sentLength + " - " + sentence.getText()); ruleMatch.setErrorLimitLang("en"); //break; -- don't stop to keep current behaviour } else { float otherRatio = (float)ruleMatches.size() / sentLength; //System.out.println("ER other??: " + otherRatio + ": " + ruleMatches.size() + " / " + sentLength + " - " + sentence.getText()); if (otherRatio > 0.66) { //System.out.println("ER other!!: " + otherRatio + ": " + ruleMatches.size() + " / " + sentLength + " - " + sentence.getText()); ruleMatch.setErrorLimitLang(NoopLanguage.SHORT_CODE); //break; -- don't stop to keep current behaviour } } } } prevStartPos = len; len += word.length() + 1; } } finally { if (monitorRules) { activeChecks.remove(monitoringText); } } /*if (sentence.getErrorLimitReached()) { return toRuleMatchArray(Collections.emptyList()); }*/ if (language.getShortCode().equals("de")) { for (RuleMatch ruleMatch : ruleMatches) { int i = 1; for (String repl : ruleMatch.getSuggestedReplacements()) { if (i <= 5 && repl.matches("[A-ZÖÄÜ][a-zöäüß]+ [a-zöäüß]+")) { // potential word with "Deppenleerzeichen": System.out.println("repl: " + sentence.getText().substring(ruleMatch.getFromPos(), ruleMatch.getToPos()) + " => " + repl + " - " + i); } i++; } } } return toRuleMatchArray(ruleMatches); } private boolean isEnglish(String word) throws IOException { for (RuleWithLanguage altRule : enSpellRules) { AnalyzedToken token = new AnalyzedToken(word, null, null); AnalyzedToken sentenceStartToken = new AnalyzedToken("", JLanguageTool.SENTENCE_START_TAGNAME, null); AnalyzedTokenReadings startTokenReadings = new AnalyzedTokenReadings(sentenceStartToken, 0); AnalyzedTokenReadings atr = new AnalyzedTokenReadings(token, 0); RuleMatch[] matches = altRule.getRule().match(new AnalyzedSentence(new AnalyzedTokenReadings[]{startTokenReadings, atr})); if (matches.length == 0) { return true; } else { if (word.endsWith(".")) { return isEnglish(word.substring(0, word.length() - 1)); } } } return false; } private List<SuggestedReplacement> calcSuggestions(String word, String cleanWord) throws IOException { List<SuggestedReplacement> suggestions = SuggestedReplacement.convert(getSuggestions(cleanWord)); if (word.endsWith(".")) { int pos = 1; for (String suggestion : getSuggestions(word)) { if (suggestions.stream().noneMatch(sr -> suggestion.equals(sr.getReplacement()))) { suggestions.add(Math.min(pos, suggestions.size()), new SuggestedReplacement(suggestion.substring(0, suggestion.length()-1))); pos += 2; // we mix the lists, as we don't know which one is the better one } } } List<SuggestedReplacement> additionalTopSuggestions = getAdditionalTopSuggestions(suggestions, cleanWord); if (additionalTopSuggestions.isEmpty() && word.endsWith(".")) { additionalTopSuggestions = getAdditionalTopSuggestions(suggestions, word). stream() .map(sugg -> { if (sugg.getReplacement().endsWith(".")) { return sugg; } else { SuggestedReplacement newSugg = new SuggestedReplacement(sugg); newSugg.setReplacement(sugg.getReplacement() + "."); return newSugg; } }).collect(Collectors.toList()); } Collections.reverse(additionalTopSuggestions); for (SuggestedReplacement additionalTopSuggestion : additionalTopSuggestions) { if (!cleanWord.equals(additionalTopSuggestion.getReplacement())) { suggestions.add(0, additionalTopSuggestion); } } List<SuggestedReplacement> additionalSuggestions = getAdditionalSuggestions(suggestions, cleanWord); for (SuggestedReplacement additionalSuggestion : additionalSuggestions) { if (!cleanWord.equals(additionalSuggestion.getReplacement())) { suggestions.addAll(additionalSuggestions); } } suggestions = filterDupes(filterSuggestions(suggestions)); // Find potentially missing compounds with privacy-friendly logging: we only log a single unknown word with no // meta data and only if it's made up of two valid words, similar to the "UNKNOWN" logging in // GermanSpellerRule: // TODO user suggestions return suggestions; } private static String cutOffDot(String s) { return s.endsWith(".") ? s.substring(0, s.length()-1) : s; } /** * @since public since 4.1 */ @Override public boolean isMisspelled(String word) { try { ensureInitialized(); boolean isAlphabetic = true; if (word.length() == 1) { // hunspell dictionaries usually do not contain punctuation isAlphabetic = Character.isAlphabetic(word.charAt(0)); } return ( isAlphabetic && !"--".equals(word) && (hunspell != null && !hunspell.spell(word)) && !ignoreWord(word) ) || isProhibited(cutOffDot(word)); } catch (IOException e) { throw new RuntimeException(e); } } public List<String> getSuggestions(String word) throws IOException { ensureInitialized(); return hunspell.suggest(word); } protected List<String> sortSuggestionByQuality(String misspelling, List<String> suggestions) { return suggestions; } protected String[] tokenizeText(String sentence) { return nonWordPattern.split(sentence); } protected String getSentenceTextWithoutUrlsAndImmunizedTokens(AnalyzedSentence sentence) { StringBuilder sb = new StringBuilder(); AnalyzedTokenReadings[] sentenceTokens = getSentenceWithImmunization(sentence).getTokens(); for (int i = 1; i < sentenceTokens.length; i++) { String token = sentenceTokens[i].getToken(); if (sentenceTokens[i].isImmunized() || sentenceTokens[i].isIgnoredBySpeller() || isUrl(token) || isEMail(token) || isQuotedCompound(sentence, i, token)) { if (isQuotedCompound(sentence, i, token)) { sb.append(' ').append(token.substring(1)); } // replace URLs and immunized tokens with whitespace to ignore them for spell checking: else if (token.length() < 20) { sb.append(WHITESPACE_ARRAY[token.length()]); } else { for (int j = 0; j < token.length(); j++) { sb.append(' '); } } } else if (token.length() > 1 && token.codePointCount(0, token.length()) != token.length()) { // some symbols such as emojis () have a string length larger than 1 List<String> emojis = EmojiParser.extractEmojis(token); for (String emoji : emojis) { token = StringUtils.replace(token, emoji, WHITESPACE_ARRAY[emoji.length()]); } sb.append(token); } else { sb.append(token); } } return sb.toString(); } protected final void ensureInitialized() throws IOException { if (needsInit) { synchronized (this) { if (needsInit) { try { init(); } finally { needsInit = false; } } } } } @Override protected synchronized void init() throws IOException { super.init(); String langCountry = language.getShortCode(); if (language.getCountries().length > 0) { langCountry += "_" + language.getCountries()[0]; } String shortDicPath = getDictFilenameInResources(langCountry); String wordChars = ""; // set dictionary only if there are dictionary files: Path affPath = null; if (JLanguageTool.getDataBroker().resourceExists(shortDicPath)) { String path = getDictionaryPath(langCountry, shortDicPath); if ("".equals(path)) { hunspell = null; } else { affPath = Paths.get(path + ".aff"); hunspell = Hunspell.getInstance(Paths.get(path + ".dic"), affPath); addIgnoreWords(); } } else if (new File(shortDicPath + ".dic").exists()) { // for dynamic languages affPath = Paths.get(shortDicPath + ".aff"); hunspell = Hunspell.getInstance(Paths.get(shortDicPath + ".dic"), affPath); } if (affPath != null) { try(Scanner sc = new Scanner(affPath)){ while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.startsWith("WORDCHARS ")) { String wordCharsFromAff = line.substring("WORDCHARS ".length()); //System.out.println("#" + wordCharsFromAff+ "#"); wordChars = "(?![" + wordCharsFromAff.replace("-", "\\-") + "])"; break; } } } } nonWordPattern = Pattern.compile(wordChars + NON_ALPHABETIC); } @NotNull protected String getDictFilenameInResources(String langCountry) { return "/" + language.getShortCode() + "/hunspell/" + langCountry + FILE_EXTENSION; } private void addIgnoreWords() throws IOException { wordsToBeIgnored.add(SpellingCheckRule.LANGUAGETOOL); wordsToBeIgnored.add(SpellingCheckRule.LANGUAGETOOLER); URL ignoreUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(getIgnoreFileName()); List<String> ignoreLines = Resources.readLines(ignoreUrl, StandardCharsets.UTF_8); for (String ignoreLine : ignoreLines) { if (!ignoreLine.startsWith(" wordsToBeIgnored.add(ignoreLine); } } } private static String getDictionaryPath(String dicName, String originalPath) throws IOException { URL dictURL = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(originalPath); String dictionaryPath; //in the webstart, java EE or OSGi bundle version, we need to copy the files outside the jar //to the local temporary directory if (StringUtils.equalsAny(dictURL.getProtocol(), "jar", "vfs", "bundle", "bundleresource")) { File tempDir = new File(System.getProperty("java.io.tmpdir")); File tempDicFile = new File(tempDir, dicName + FILE_EXTENSION); JLanguageTool.addTemporaryFile(tempDicFile); try (InputStream dicStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath)) { fileCopy(dicStream, tempDicFile); } File tempAffFile = new File(tempDir, dicName + ".aff"); JLanguageTool.addTemporaryFile(tempAffFile); if (originalPath.endsWith(FILE_EXTENSION)) { originalPath = originalPath.substring(0, originalPath.length() - FILE_EXTENSION.length()) + ".aff"; } try (InputStream affStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath)) { fileCopy(affStream, tempAffFile); } dictionaryPath = tempDir.getAbsolutePath() + "/" + dicName; } else { int suffixLength = FILE_EXTENSION.length(); try { dictionaryPath = new File(dictURL.toURI()).getAbsolutePath(); dictionaryPath = dictionaryPath.substring(0, dictionaryPath.length() - suffixLength); } catch (URISyntaxException e) { return ""; } } return dictionaryPath; } private static void fileCopy(InputStream in, File targetFile) throws IOException { try (OutputStream out = new FileOutputStream(targetFile)) { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); } } }
package com.SSUJ.world; import com.SSUJ.animal.Animal; import com.SSUJ.animal.EatType; import com.SSUJ.tile.Tile; import com.SSUJ.vegetation.Vegetation; import java.util.ArrayList; import java.util.List; import java.util.Random; public class World { private int x; // Size of map in x dir private int y; // Size of map in y dir private Tile[][] map; // The map array is formatted like: Tile[y][x] WHERE top left corner is 0,0 private int day; public void generate() { //this.x = x; //this.y = y; Already done this.map = new Tile[this.y][this.x; this.day = 0; /** * Random number generator is used to set animal, vegetation, exhaustion level */ Random rn = new Random(); //Tile[][] mapp = new Tile[x][y]; for(int n=0;n<y;n++){ /*alternative method of printing to console while generating map if((n % 500)==0){ System.out.print("x: "); System.out.println(n); }*/ for(int m=0;m<x;m++){ int randomExhaustion = rn.nextInt(2); int animalChance = rn.nextInt(5); int vegetationChance = rn.nextInt(4); int randomAnimal = 10; int randomVegetation = 3; if(animalChance == 1) randomAnimal = rn.nextInt(10); if(vegetationChance == 1) randomVegetation = rn.nextInt(3); //sim.initialize(); Tile genTile = new Tile(); genTile.generate(randomAnimal,randomVegetation,randomExhaustion); this.map[n][m] = genTile; /*The following print statements are used if Trevor wants to see the tile as it is generated*/ /* if(genTile.getAnimal()!= null){ System.out.print("x: "); System.out.print(n); System.out.print(" y: "); System.out.println(m); System.out.print(" Animal: "); System.out.println(genTile.getAnimal()); System.out.print(" Vegetation: "); System.out.println(genTile.getVegetation()); System.out.print(" ExhuastionLevel: "); System.out.println(genTile.getExhaustionLevel()); } */ } } } public int getDay(){ return this.day; } public Tile[][] getMap(){ return this.map; } public void setX(int x){ this.x = x; } public void setY(int y){ this.y = y; } public int getY(){ return this.y; } public int getX(){ return this.x; } public List<String> nextDay() { List<String> events = new ArrayList<>(); Random rand = new Random(); events.add("Day: " + this.day); for(int m = 0; m < y; m++) // Y direction { for(int n = 0; n < x; n++) // X direction { if(getTile(n, m).getAnimal() != null && !(getTile(n, m).getAnimal().getDone())) { Tile tile = getTile(n, m); Animal animal = tile.getAnimal(); Vegetation vegetation = tile.getVegetation(); int speed = animal.getSpeed(); // Handle hunger drop for the movement animal.changeHunger(speed * -1); int i = 0; // Overall Change in X direction int j = 0; // Overall Change in Y direction while(speed > 0) { int direction = rand.nextInt(4) + 1; //1 is up, 2 is right, 3 is down, 4 is left switch (direction) { case 1: j--; break; case 2: i++; break; case 3: j++; break; case 4: i--; break; } Tile moveTile = getTile(m + j, n + i); int exhaustion = moveTile.getExhaustionLevel(); speed -= exhaustion; speed -= 1; } int m2 = m + j; // Coords of the destination tile in Y direction int n2 = n + i; // Coords of the destination tile in X direction // Ensuring we stay on the map if(m2 < 0) m2 = 0; if(n2 < 0) n2 = 0; if(m2 >= this.y) m2 = this.y - 1; if(n2 >= this.x) n2 = this.x - 1; if(n2 == n && m2 == m) { events.add(animal.getName() + " didn't move."); // Drop animal health if its hungry if(animal.getHunger() <= 0) { int dmg = (int)(Math.ceil((double)animal.getMaxHealth() * 0.05)); animal.changeHealth(dmg); if(animal.dead()) { tile.setAnimal(null); events.add(animal.getName() + " died by starvation."); } else { events.add(animal.getName() + " is slowly starving to death."); } } } else { events.add(animal.getName() + " at (" + n + "," + m + ") moved to (" + n2 + "," + m2 + ")."); Tile tile2 = getTile(n2, m2); Animal animal2 = tile2.getAnimal(); Vegetation vegetation2 = tile2.getVegetation(); boolean killed = false; // Collision will happen if(animal2 != null) { // Animal on Animal collision // Generating the overall eat level by taking into account predator vs prey int eatLevel = animal.getEatsLevel(); if(animal.getEats() == EatType.PREDATOR) eatLevel += 1000; int eatLevel2 = animal2.getEatsLevel(); if(animal2.getEats() == EatType.PREDATOR) eatLevel2 += 1000; if(eatLevel >= eatLevel2) { // Animal eats the animal on the new tile animal.changeHunger(animal2.kill()); tile2.setAnimal(animal); tile.setAnimal(null); events.add(animal.getName() + " encountered a " + animal2.getName() + " and killed it."); } else { // Animal is eaten by the animal on the new tile animal2.changeHunger(animal.kill()); tile.setAnimal(null); killed = true; events.add(animal.getName() + " encountered a " + animal2.getName() + " and was killed by it."); } } else if(vegetation2 != null) { // Animal on plant collision. tile2.setAnimal(animal); tile.setAnimal(null); tile2.getAnimal().changeHunger(vegetation2.eat()); tile2.setVegetation(null); events.add(animal.getName() + " found " + vegetation2.getName() + " and ate it."); } else { // Simple animal movement tile2.setAnimal(animal); tile.setAnimal(null); } // Drop animal health if its hungry if(!killed && animal.getHunger() <= 0) { int dmg = (int)(Math.ceil((double)animal.getMaxHealth() * 0.05)); animal.changeHealth(dmg); if(animal.dead()) { tile2.setAnimal(null); events.add(animal.getName() + " died by starvation."); } else { events.add(animal.getName() + " is slowly starving to death."); } } } // Marking the animal as having moved already this day animal.setDone(true); } } } day++; // Resetting the animals to be ready for a new day for(int m = 0; m < y; m++) // Y direction { for(int n = 0; n < x; n++) // X direction { if(getTile(n, m).getAnimal() != null) { getTile(n, m).getAnimal().setDone(false); } } } return events; } public Tile getTile(int x, int y) { return this.map[x][y]; } public int killAnimal(int x, int y) { Tile tile = getTile(x, y); if(tile.getAnimal() != null) { int food = tile.getAnimal().kill(); tile.setAnimal(null); return food; } return 0; } public int killVegetation(int x, int y) { Tile tile = getTile(x, y); if(tile.getVegetation() != null) { int food = tile.getVegetation().eat(); tile.setVegetation(null); return food; } return 0; } }
package com.dtw; import com.matrix.ColMajorCell; import java.util.Iterator; import java.util.Arrays; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; abstract public class SearchWindow { // PRIVATE DATA private final int[] minValues; private final int[] maxValues; private final int maxJ; private int size; private int modCount; // CONSTRUCTOR public SearchWindow(int tsIsize, int tsJsize) { minValues = new int[tsIsize]; maxValues = new int[tsIsize]; Arrays.fill(minValues, -1); maxJ = tsJsize-1; size = 0; modCount = 0; } // PUBLIC FUNCTIONS public final boolean isInWindow(int i, int j) { return (i>=minI()) && (i<=maxI()) && (minValues[i]<=j) && (maxValues[i]>=j); } public final int minI() { return 0; } public final int maxI() { return minValues.length-1; } public final int minJ() { return 0; } public final int maxJ() { return maxJ; } public final int minJforI(int i) { return minValues[i]; } public final int maxJforI(int i) { return maxValues[i]; } public final int size() { return size; } // Iterates through all cells in the search window in the order that Dynamic // Time Warping needs to evaluate them. (first to last column (0..maxI), // bottom up (o..maxJ)) public Iterator iterator() { return new SearchWindowIterator(this); } public final String toString() { final StringBuffer outStr = new StringBuffer(); for (int i=minI(); i<=maxI(); i++) { outStr.append("i=" + i + ", j=" + minValues[i] + "..." + maxValues[i]); if (i != maxI()) outStr.append("\n"); } // end for loop return outStr.toString(); } // end toString() protected int getModCount() { return modCount; } // PROTECTED FUNCTIONS // Expands the current window by a s pecified radius. protected final void expandWindow(int radius) { if (radius > 0) { // Expand the search window by one before expanding by the remainder of the radius because the function // "expandSearchWindow(.) may not work correctly if the path has a width of only 1. expandSearchWindow(1); expandSearchWindow(radius-1); } } protected void expandSearchWindow(int radius) { if (radius > 0) // if radius <=0 then no search is necessary, use the current search window { // Add all cells in the current Window to an array, iterating through the window and expanding the window // at the same time is not possible because the window can't be changed during iteration through the cells. final ArrayList windowCells = new ArrayList(this.size()); for (final Iterator cellIter=this.iterator(); cellIter.hasNext();) windowCells.add(cellIter.next()); for (int cell=0; cell<windowCells.size(); cell++) { final ColMajorCell currentCell = (ColMajorCell)windowCells.get(cell); if ( (currentCell.getCol() != minI()) && (currentCell.getRow() != maxJ()) )// move to upper left if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()-radius; final int targetRow = currentCell.getRow()+radius; if ( (targetCol>=minI()) && (targetRow<=maxJ())) markVisited(targetCol, targetRow); else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = Math.max(minI()-targetCol, targetRow-maxJ()); markVisited(targetCol+cellsPastEdge, targetRow-cellsPastEdge); } // end if } // end if if (currentCell.getRow() != maxJ()) // move up if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol(); final int targetRow = currentCell.getRow()+radius; if (targetRow <= maxJ()) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = targetRow-maxJ(); markVisited(targetCol, targetRow-cellsPastEdge); } // end if } // end if if ((currentCell.getCol() != maxI()) && (currentCell.getRow() != maxJ())) // move to upper-right if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()+radius; final int targetRow = currentCell.getRow()+radius; if ( (targetCol<=maxI()) && (targetRow<=maxJ())) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = Math.max(targetCol-maxI(), targetRow-maxJ()); markVisited(targetCol-cellsPastEdge, targetRow-cellsPastEdge); } // end if } // end if if (currentCell.getCol() != minI()) // move left if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()-radius; final int targetRow = currentCell.getRow(); if (targetCol >= minI()) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = minI()-targetCol; markVisited(targetCol+cellsPastEdge, targetRow); } // end if } // end if if (currentCell.getCol() != maxI()) // move right if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()+radius; final int targetRow = currentCell.getRow(); if (targetCol <= maxI()) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = targetCol-maxI(); markVisited(targetCol-cellsPastEdge, targetRow); } // end if } // end if if ( (currentCell.getCol() != minI()) && (currentCell.getRow() != minJ()) ) // move to lower-left if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()-radius; final int targetRow = currentCell.getRow()-radius; if ( (targetCol>=minI()) && (targetRow>=minJ())) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = Math.max(minI()-targetCol, minJ()-targetRow); markVisited(targetCol+cellsPastEdge, targetRow+cellsPastEdge); } // end if } // end if if (currentCell.getRow() != minJ()) // move down if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol(); final int targetRow = currentCell.getRow()-radius; if (targetRow >= minJ()) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = minJ()-targetRow; markVisited(targetCol, targetRow+cellsPastEdge); } // end if } // end if if ((currentCell.getCol() != maxI()) && (currentCell.getRow() != minJ())) // move to lower-right if possible { // Either extend full search radius or some fraction until edges of matrix are met. final int targetCol = currentCell.getCol()+radius; final int targetRow = currentCell.getRow()-radius; if ( (targetCol<=maxI()) && (targetRow>=minJ())) markVisited(targetCol, targetRow); // radius does not go past the edges of the matrix else { // Expand the window only to the edge of the matrix. final int cellsPastEdge = Math.max(targetCol-maxI(), minJ()-targetRow); markVisited(targetCol-cellsPastEdge, targetRow+cellsPastEdge); } // end if } // end if } // end for loop } // end if } // end expandWindow(.) // Raturns true if the window is modified. protected final void markVisited(int col, int row) { if (minValues[col] == -1) // first value is entered in the column { minValues[col] = row; maxValues[col] = row; this.size++; modCount++; // stucture has been changed //return true; } else if (minValues[col] > row) // minimum range in the column is expanded { this.size += minValues[col]-row; minValues[col] = row; modCount++; // stucture has been changed } else if (maxValues[col] < row) // maximum range in the column is expanded { this.size += row-maxValues[col]; maxValues[col] = row; modCount++; } // end if } // end markVisited(.) // A private class that is a fail-fast iterator through the search window. protected class SearchWindowIterator implements Iterator { // PRIVATE DATA protected int currentI; protected int currentJ; private final SearchWindow window; private boolean hasMoreElements; private final int expectedModCount; // CONSTRUCTOR protected SearchWindowIterator(SearchWindow w) { // Intiialize values window = w; hasMoreElements = window.size()>0; currentI = window.minI(); currentJ = window.minJ(); expectedModCount = w.modCount; } // PUBLIC FUNCTIONS public boolean hasNext() { return hasMoreElements; } public Object next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); else if (!hasMoreElements) throw new NoSuchElementException(); else { final ColMajorCell cell = new ColMajorCell(currentI, currentJ); if (++currentJ > window.maxJforI(currentI)) { if (++currentI <= window.maxI()) currentJ = window.minJforI(currentI); else hasMoreElements = false; } // end if return cell; } // end if } // end next() public void remove() { throw new UnsupportedOperationException(); } } // end inner class SearchWindowIterator } // end SearchWindow
package commands; import backendExceptions.BackendException; import commandParser.CommandFactory; import communicator.IVariableContainer; import View.SlogoView; import turtle.Turtle; /** * * Abstract class for a Turtle command. The update method will be implemented and * returns the turtle object that can be manipulated by other commands. All other * types of commands will extend the BaseCommand, such as commands that only * modify the view, commands that are conditional, mathematical operations. * */ public abstract class BaseCommand { private BaseCommand myNextCommand; private BaseCommand myInternalCommand; private String myLeftoverString = ""; private boolean myExpressionFlag; protected final String COMMAND_DELIMITER = "\\s+"; /** * * @param userInput * @throws BackendException TODO */ public BaseCommand(String userInput, boolean isExpression) throws BackendException { myExpressionFlag = isExpression; parseArguments(userInput); } /** * Method returns the computation of the turtle command * @param variableContainer TODO * @throws BackendException TODO * */ public abstract double execute(SlogoView view, Turtle turtle, IVariableContainer variableContainer) throws BackendException; protected BaseCommand getNextCommand(){ return myNextCommand; } protected abstract void parseArguments(String userInput) throws BackendException; protected void setNextCommand(BaseCommand command){ myNextCommand = command; } protected BaseCommand getInternalCommand(){ return myInternalCommand; } protected void setInternalCommand(BaseCommand command){ myInternalCommand = command; } public String getLeftoverString(){ return myLeftoverString; } protected void setLeftoverCommands(String string){ if(myExpressionFlag){ myLeftoverString = string; } else if(string != null && string != ""){ myNextCommand = CommandFactory.createCommand(string, false); } } }
package charts.builder; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.jfree.data.category.DefaultCategoryDataset; import charts.Drawable; import charts.TrackingTowardsTargets; import charts.spreadsheet.DataSource; import charts.spreadsheet.SpreadsheetHelper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; public class TrackingTowardsTagetsBuilder extends DefaultSpreadsheetChartBuilder { private static enum Series { CANE("Cane"), HORTICULTURE("Horticulture"), GRAZING("Grazing"), SEDIMENT("Sediment"), TOTAL_NITROGEN("Total nitrogen"), PESTICIDES("Pesticides"); private String name; private Series(String name) { this.name = name; } @Override public String toString() { return name; } } private static final ImmutableMap<Series, Integer> ROW = new ImmutableMap.Builder<Series, Integer>() .put(Series.CANE, 1) .put(Series.HORTICULTURE, 2) .put(Series.GRAZING, 3) .put(Series.SEDIMENT, 4) .put(Series.TOTAL_NITROGEN, 5) .put(Series.PESTICIDES, 6) .build(); public TrackingTowardsTagetsBuilder() { super(Lists.newArrayList(ChartType.TTT_CANE_AND_HORT, ChartType.TTT_GRAZING, ChartType.TTT_NITRO_AND_PEST, ChartType.TTT_SEDIMENT)); } @Override boolean canHandle(DataSource datasource) { try { return "tracking towards tagets".equalsIgnoreCase( datasource.select("A1").format("value")); } catch(Exception e) { return false; } } @Override Chart build(DataSource datasource, final ChartType type, final Region region, final Map<String, String[]> query) { if(region == Region.GBR) { SpreadsheetHelper helper = new SpreadsheetHelper(datasource); final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); final double target; final String targetBy; switch(type) { case TTT_CANE_AND_HORT: addSeries(helper, dataset, Series.CANE); addSeries(helper, dataset, Series.HORTICULTURE); target = getTarget(helper, Series.CANE); targetBy = getTargetBy(helper, Series.CANE); break; case TTT_GRAZING: addSeries(helper, dataset, Series.GRAZING); target = getTarget(helper, Series.GRAZING); targetBy = getTargetBy(helper, Series.GRAZING); break; case TTT_NITRO_AND_PEST: addSeries(helper, dataset, Series.TOTAL_NITROGEN); addSeries(helper, dataset, Series.PESTICIDES); target = getTarget(helper, Series.TOTAL_NITROGEN); targetBy = getTargetBy(helper, Series.TOTAL_NITROGEN); break; case TTT_SEDIMENT: addSeries(helper, dataset, Series.SEDIMENT); target = getTarget(helper, Series.SEDIMENT); targetBy = getTargetBy(helper, Series.SEDIMENT); break; default: throw new RuntimeException("chart type not supported "+type.toString()); } return new AbstractChart(query) { @Override public ChartDescription getDescription() { return new ChartDescription(type, region); } @Override public Drawable getChart() { return new TrackingTowardsTargets().createChart(type, target, targetBy, dataset, getChartSize(query, 750, 500)); } @Override public String getCSV() throws UnsupportedFormatException { throw new Chart.UnsupportedFormatException(); }}; } return null; } private void addSeries(SpreadsheetHelper helper, DefaultCategoryDataset dataset, Series series) { Integer row = ROW.get(series); if(row == null) { throw new RuntimeException("no row configured for series "+series); } List<String> columns = getColumns(helper); for(int col=0; col<columns.size(); col++) { String s = helper.selectText(row, col+3); try { Double value = new Double(s); dataset.addValue(value, series.toString(), columns.get(col)); } catch(Exception e) { dataset.addValue(null, series.toString(), columns.get(col)); } } } private List<String> getColumns(SpreadsheetHelper helper) { List<String> columns = Lists.newArrayList(); for(int col=3; true; col++) { String s = helper.selectText(0, col); if(StringUtils.isBlank(s)) { break; } columns.add(s); } return columns; } private double getTarget(SpreadsheetHelper helper, Series series) { return helper.selectDouble(ROW.get(series), 1); } private String getTargetBy(SpreadsheetHelper helper, Series series) { return helper.selectInt(ROW.get(series), 2).toString(); } }
package com.dom_distiller.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.js.JsExport; import com.google.gwt.core.client.js.JsProperty; import com.google.gwt.core.client.js.JsType; import com.google.gwt.user.client.Window; import java.util.Map; public class JsTestEntry implements EntryPoint { public void onModuleLoad() { } @JsType interface TestSuiteResults { @JsProperty void setLog(String log); @JsProperty void setSuccess(boolean success); @JsProperty void setNumTests(int i); @JsProperty void setFailed(int i); @JsProperty void setSkipped(int i); } private static native TestSuiteResults createResults() /*-{ return new Object(); }-*/; @JsExport public static TestSuiteResults run() { String filter = Window.Location.getParameter("filter"); JsTestSuiteBuilder builder = GWT.<JsTestSuiteBuilder>create(JsTestSuiteBuilder.class); TestLogger logger = new TestLogger(); Map<String, JsTestSuiteBase.TestCaseResults> results = builder.build().run(logger, filter); return createTestSuiteResults(results, logger); } private static TestSuiteResults createTestSuiteResults( Map<String, JsTestSuiteBase.TestCaseResults> results, TestLogger logger) { int numTests = 0, failed = 0, skipped = 0; TestSuiteResults response = createResults(); for (Map.Entry<String, JsTestSuiteBase.TestCaseResults> testCaseEntry : results.entrySet()) { for (Map.Entry<String, JsTestSuiteBase.TestResult> testEntry : testCaseEntry.getValue().getResults().entrySet()) { numTests++; if (testEntry.getValue().skipped()) { skipped++; } else if (!testEntry.getValue().success()) { failed++; } } } response.setSuccess(failed == 0); response.setNumTests(numTests); response.setFailed(failed); response.setSkipped(skipped); response.setLog(logger.getLog()); return response; } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // 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 jodd.util; import jodd.core.JoddCore; import jodd.core.JoddCoreDefaults; public class UnsafeUtil { // IMPORTANT - the order of declaration here is important! we need to detect // first the Android, and then to check for the unsafe field. private static final boolean IS_ANDROID = SystemUtil.isHostAndroid(); private static final boolean HAS_UNSAFE = !IS_ANDROID && UnsafeInternal.hasUnsafe(); private static final JoddCoreDefaults JODD_CORE_DEFAULTS = JoddCore.get().defaults(); /** * Returns <code>true</code> if system has the <code>Unsafe</code>. */ public static boolean hasUnsafe() { return HAS_UNSAFE; } /** * Returns String characters in most performing way. * If possible, the inner <code>char[]</code> will be returned. * If not, <code>toCharArray()</code> will be called. * Returns <code>null</code> when argument is <code>null</code>. */ public static char[] getChars(final String string) { if (string == null) { return null; } if (!HAS_UNSAFE || !JODD_CORE_DEFAULTS.isUnsafeUsed()) { return string.toCharArray(); } return UnsafeInternal.unsafeGetChars(string); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // 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 jodd.io; import jodd.util.StringUtil; import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; class FileUtilTest { protected String dataRoot; protected String utfdataRoot; @BeforeEach void setUp() throws Exception { if (dataRoot != null) { return; } URL data = FileUtilTest.class.getResource("data"); dataRoot = data.getFile(); data = FileUtilTest.class.getResource("utf"); utfdataRoot = data.getFile(); } @Test void testFileManipulation() throws IOException { FileUtil.copy(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data")); assertFalse(FileUtil.isNewer(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data"))); assertFalse(FileUtil.isOlder(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data"))); FileUtil.delete(new File(dataRoot, "sb1.data")); } @Test void testString() { String s = "This is a test file\nIt only has\nthree lines!!"; try { FileUtil.writeString(new File(dataRoot, "test.txt"), s); } catch (Exception ex) { fail("FileUtil.writeString " + ex.toString()); } String s2 = null; try { s2 = FileUtil.readString(dataRoot + "/test.txt"); } catch (Exception ex) { fail("FileUtil.readString " + ex.toString()); } assertEquals(s, s2); // test unicode chars (i.e. greater then 255) char[] buf = s.toCharArray(); buf[0] = 256; s = new String(buf); try { FileUtil.writeString(dataRoot + "/test.txt", s); } catch (Exception ex) { fail("FileUtil.writeString " + ex.toString()); } try { s2 = FileUtil.readString(dataRoot + "/test.txt"); } catch (Exception ex) { fail("FileUtil.readString " + ex.toString()); } assertEquals(s.substring(1), s2.substring(1)); assertEquals(s.charAt(0), s2.charAt(0)); try { FileUtil.delete(dataRoot + "/test.txt"); } catch (IOException ioex) { fail("FileUtil.delete" + ioex.toString()); } } @Test void testUnicodeString() { String s = "This is a test file\nIt only has\nthree lines!!"; char[] buf = s.toCharArray(); buf[0] = 256; s = new String(buf); try { FileUtil.writeString(dataRoot + "/test2.txt", s, "UTF-16"); } catch (Exception ex) { fail("FileUtil.writeString " + ex.toString()); } String s2 = null; try { s2 = FileUtil.readString(dataRoot + "/test2.txt", "UTF-16"); } catch (Exception ex) { fail("FileUtil.readString " + ex.toString()); } assertEquals(s, s2); try { FileUtil.delete(dataRoot + "/test2.txt"); } catch (IOException ioex) { fail("FileUtil.delete" + ioex.toString()); } } @Test void testFileManipulations() { String root = dataRoot + "/file/"; String tmp = root + "tmp/"; String tmp2 = root + "xxx/"; String tmp3 = root + "zzz/"; // copy try { FileUtil.copyFile(root + "a.txt", root + "w.txt"); FileUtil.copyFile(root + "a.png", root + "w.png"); FileUtil.copyFile(root + "a.txt", root + "w.txt"); } catch (IOException ioex) { fail(ioex.toString()); } // mkdirs try { FileUtil.mkdir(tmp); FileUtil.mkdirs(tmp + "x/"); FileUtil.copyFileToDir(root + "a.txt", tmp); FileUtil.copyFileToDir(root + "a.png", tmp); } catch (IOException ioex) { fail(ioex.toString()); } // don't overwrite try { FileUtil.copyFileToDir(root + "a.txt", tmp, FileUtil.params().setOverwrite(false)); fail("copy file don't overwrite"); } catch (IOException e) { // ignore } // move try { FileUtil.moveFile(root + "w.txt", tmp + "w.txt"); FileUtil.moveFileToDir(root + "w.png", tmp); } catch (IOException ioex) { fail(ioex.toString()); } try { FileUtil.moveFileToDir(root + "w.png", tmp, FileUtil.cloneParams().setOverwrite(false)); fail("move file don't overwrite"); } catch (IOException e) { // ignore } // delete try { FileUtil.deleteFile(tmp + "a.txt"); FileUtil.deleteFile(tmp + "a.png"); FileUtil.deleteFile(tmp + "w.txt"); FileUtil.deleteFile(tmp + "w.png"); } catch (IOException ioex) { fail(ioex.toString()); } try { FileUtil.deleteFile(tmp + "a.txt"); fail("delete file strict delete"); } catch (IOException e) { // ignore } // movedir try { FileUtil.moveDir(tmp, tmp2); } catch (IOException ioex) { fail(ioex.toString()); } // copyDir try { FileUtil.copyDir(tmp2, tmp3); } catch (IOException ioex) { fail(ioex.toString()); } // deleteDir try { FileUtil.deleteDir(tmp2); FileUtil.deleteDir(tmp3); } catch (IOException ioex) { fail(ioex.toString()); } } @Test void testBytes() { try { File file = new File(dataRoot + "/file/a.txt"); byte[] bytes = FileUtil.readBytes(dataRoot + "/file/a.txt"); assertEquals(file.length(), bytes.length); String content = new String(bytes); content = StringUtil.remove(content, '\r'); assertEquals("test file\n", content); } catch (IOException ioex) { fail(ioex.toString()); } } @Test void testUTFReads() throws IOException { String content = FileUtil.readUTFString(new File(utfdataRoot, "utf-8.txt")); content = content.replace("\r\n", "\n"); String content8 = FileUtil.readString(new File(utfdataRoot, "utf-8.txt"), "UTF-8"); content8 = content8.replace("\r\n", "\n"); assertEquals(content, content8); String content1 = FileUtil.readUTFString(new File(utfdataRoot, "utf-16be.txt")); content1 = content1.replace("\r\n", "\n"); assertEquals(content, content1); String content16 = FileUtil.readString(new File(utfdataRoot, "utf-16be.txt"), "UTF-16BE"); content16 = content16.replace("\r\n", "\n"); assertEquals(content, content16); String content162 = FileUtil.readString(new File(utfdataRoot, "utf-16be.txt"), "UTF-16"); content162 = content162.replace("\r\n", "\n"); assertEquals(content, content162); String content2 = FileUtil.readUTFString(new File(utfdataRoot, "utf-16le.txt")); content2 = content2.replace("\r\n", "\n"); assertEquals(content, content2); String content163 = FileUtil.readString(new File(utfdataRoot, "utf-16le.txt"), "UTF-16LE"); content163 = content163.replace("\r\n", "\n"); assertEquals(content, content163); } @ParameterizedTest (name = "{index} : FileUtil @CsvSource( { "md5, 529a2cfd3346c7fe17b845b6ec90fcfd", "sha1, 7687b985b2eeff4a981480cead1787bd3f26929c", "sha256, b2a3dec0059df342e9b33721957fd54221ab7fb7daa99d9f35af729dc2568e51", "sha384, 1eb67f4b35ae69bbd815dbceee9584c9a65b82e8a209b0a3ab9e6def0a74cf5915228ce32f6154ba5c9ee6dfc66f6414", "sha512, 4b53d8ca344fc63dd0a69b2ef4c5275279b4c31a834d5e0501a0ab646d1cc56f15e45a019e3f46597be288924b8b6fba19e4ebad1552f5007d56e7f12c3cb1d2" } ) @DisplayName(value = "tests for digest-algorithms") void testDigestAlgorithms(final String method, final String expected) throws Exception { Method declaredMethod = FileUtil.class.getMethod(method, File.class); File file = new File(FileUtilTest.class.getResource("data/file/a.png").toURI()); final String actual = (String) declaredMethod.invoke(null, file); // asserts assertEquals(expected, actual.toLowerCase()); } }
package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A cache of DNS records. The cache obeys TTLs, so items are purged after * their validity period is complete. Negative answers are cached, to * avoid repeated failed DNS queries. The credibility of each RRset is * maintained, so that more credible records replace less credible records, * and lookups can specify the minimum credibility of data they are requesting. * @see RRset * @see Credibility * * @author Brian Wellington */ public class Cache extends NameSet { private class Element { Name name; RRset rrset; short type; byte credibility; long timeIn; long ttl; int srcid; Thread tid; public Element(Name name, long ttl, byte cred, int src, short type) { this.name = name; rrset = null; this.type = type; credibility = cred; this.ttl = (long)ttl & 0xFFFFFFFFL; srcid = src; timeIn = System.currentTimeMillis(); tid = Thread.currentThread(); } public Element(Record r, byte cred, int src) { name = r.getName(); rrset = new RRset(); type = rrset.getType(); credibility = cred; timeIn = System.currentTimeMillis(); ttl = -1; srcid = src; update(r); tid = Thread.currentThread(); } public Element(RRset r, byte cred, int src) { name = r.getName(); rrset = r; type = r.getType(); credibility = cred; timeIn = System.currentTimeMillis(); ttl = (long)r.getTTL() & 0xFFFFFFFFL; srcid = src; tid = Thread.currentThread(); } public final void update(Record r) { rrset.addRR(r); timeIn = System.currentTimeMillis(); if (ttl < 0) ttl = (long)r.getTTL() & 0xFFFFFFFFL; } public void deleteRecord(Record r) { rrset.deleteRR(r); } public final boolean expiredTTL() { long now = System.currentTimeMillis(); long expire = timeIn + (1000 * ttl); return (now > expire); } public final boolean TTL0Ours() { return (ttl == 0 && tid == Thread.currentThread()); } public final boolean TTL0NotOurs() { return (ttl == 0 && tid != Thread.currentThread()); } public final String toString() { StringBuffer sb = new StringBuffer(); if (rrset != null) sb.append(rrset); else if (type == 0) sb.append("NXDOMAIN " + name); else sb.append("NXRRSET " + name + " " + Type.string(type)); sb.append(" cl = "); sb.append(credibility); sb.append("\n"); return sb.toString(); } } private class CacheCleaner extends Thread { public CacheCleaner() { setDaemon(true); setName("CacheCleaner"); } public void run() { while (true) { long now = System.currentTimeMillis(); long next = now + cleanInterval * 60 * 1000; while (now < next) { try { Thread.sleep(next - now); } catch (InterruptedException e) { now = System.currentTimeMillis(); continue; } } Iterator it = names(); while (it.hasNext()) { Name name = (Name) it.next(); TypeMap tm = findName(name); if (tm == null) continue; Object [] elements; elements = tm.getAll(); if (elements == null) continue; for (int i = 0; i < elements.length; i++) { Element element = (Element) elements[i]; if (element.ttl == 0 && element.timeIn >= now) continue; if (element.expiredTTL()) removeSet(name, element.type, element); } } } } } private Verifier verifier; private boolean secure; private int maxncache = -1; private long cleanInterval = 30; private Thread cleaner; private short dclass; /** * Creates an empty Cache * * @param dclass The dns class of this cache * @see DClass */ public Cache(short dclass) { super(true); cleaner = new CacheCleaner(); this.dclass = dclass; } /** * Creates an empty Cache for class IN. * @see DClass */ public Cache() { this(DClass.IN); } /** Empties the Cache. */ public void clearCache() { clear(); } /** * Creates a Cache which initially contains all records in the specified file. */ public Cache(String file) throws IOException { super(true); cleaner = new CacheCleaner(); Master m = new Master(file); Record record; while ((record = m.nextRecord()) != null) addRecord(record, Credibility.HINT, m); } /** * Adds a record to the Cache. * @param r The record to be added * @param cred The credibility of the record * @param o The source of the record (this could be a Message, for example) * @see Record */ public void addRecord(Record r, byte cred, Object o) { Name name = r.getName(); short type = r.getRRsetType(); if (!Type.isRR(type)) return; int src = (o != null) ? o.hashCode() : 0; Element element = (Element) findExactSet(name, type); if (element == null || cred > element.credibility) addSet(name, type, element = new Element(r, cred, src)); else if (cred == element.credibility) { if (element.srcid != src) { element.rrset.clear(); element.srcid = src; } element.update(r); } } /** * Adds an RRset to the Cache. * @param r The RRset to be added * @param cred The credibility of these records * @param o The source of this RRset (this could be a Message, for example) * @see RRset */ public void addRRset(RRset rrset, byte cred, Object o) { Name name = rrset.getName(); short type = rrset.getType(); int src = (o != null) ? o.hashCode() : 0; if (verifier != null) rrset.setSecurity(verifier.verify(rrset, this)); if (secure && rrset.getSecurity() < DNSSEC.Secure) return; Element element = (Element) findExactSet(name, type); if (element == null || cred > element.credibility) addSet(name, type, new Element(rrset, cred, src)); } /** * Adds a negative entry to the Cache. * @param name The name of the negative entry * @param type The type of the negative entry * @param ttl The ttl of the negative entry * @param cred The credibility of the negative entry * @param o The source of this data */ public void addNegative(short rcode, Name name, short type, long ttl, byte cred, Object o) { if (rcode == Rcode.NXDOMAIN) type = 0; int src = (o != null) ? o.hashCode() : 0; Element element = (Element) findExactSet(name, type); if (element == null || cred > element.credibility) addSet(name, type, new Element(name, ttl, cred, src, type)); } /** * Looks up Records in the Cache. This follows CNAMEs and handles negatively * cached data. * @param name The name to look up * @param type The type to look up * @param minCred The minimum acceptable credibility * @return A SetResponse object * @see SetResponse * @see Credibility */ public SetResponse lookupRecords(Name name, short type, byte minCred) { SetResponse cr = null; Object o = findSets(name, type); if (o == null || o instanceof TypeMap) { /* * The name exists, but the type was not found. Or, the * name does not exist and no parent does either. Punt. */ return new SetResponse(SetResponse.UNKNOWN); } Object [] objects; if (o instanceof Element) objects = new Object[] {o}; else objects = (Object[]) o; int nelements = 0; for (int i = 0; i < objects.length; i++) { Element element = (Element) objects[i]; if (element.TTL0Ours()) { removeSet(name, type, element); nelements++; } else if (element.TTL0NotOurs()) { objects[i] = null; } else if (element.expiredTTL()) { removeSet(name, type, element); objects[i] = null; } else if (element.credibility < minCred) { objects[i] = null; } else { nelements++; } } if (nelements == 0) { /* We have data, but can't use it. Punt. */ return new SetResponse(SetResponse.UNKNOWN); } /* * We have something at the name. It could be the answer, * a CNAME, DNAME, or NS, or a negative cache entry. * * Ignore wildcards, since it's pretty unlikely that any will be * cached. The occasional extra query is easily balanced by the * reduced number of lookups. */ for (int i = 0; i < objects.length; i++) { if (objects[i] == null) continue; Element element = (Element) objects[i]; RRset rrset = element.rrset; /* Is this a negatively cached entry? */ if (rrset == null) { /* * If this is an NXDOMAIN entry, return NXDOMAIN. */ if (element.type == 0) return new SetResponse(SetResponse.NXDOMAIN); /* * If we're not looking for type ANY, return NXRRSET. * Otherwise ignore this. */ if (type != Type.ANY) return new SetResponse(SetResponse.NXRRSET); else continue; } int rtype = rrset.getType(); Name rname = rrset.getName(); if (name.equals(rname)) { if (type != Type.CNAME && type != Type.ANY && rtype == Type.CNAME) return new SetResponse(SetResponse.CNAME, rrset); else if (type != Type.NS && type != Type.ANY && rtype == Type.NS) return new SetResponse(SetResponse.DELEGATION, rrset); else { if (cr == null) cr = new SetResponse (SetResponse.SUCCESSFUL); cr.addRRset(rrset); } } else if (name.subdomain(rname)) { if (rtype == Type.DNAME) return new SetResponse(SetResponse.DNAME, rrset); else if (rtype == Type.NS) return new SetResponse(SetResponse.DELEGATION, rrset); } } /* * As far as I can tell, the only legitimate time cr will be null is * if we queried for ANY and only saw negative responses, but not an * NXDOMAIN. Return UNKNOWN. */ if (cr == null && type == Type.ANY) return new SetResponse(SetResponse.UNKNOWN); return cr; } private RRset [] findRecords(Name name, short type, byte minCred) { SetResponse cr = lookupRecords(name, type, minCred); if (cr.isSuccessful()) return cr.answers(); else return null; } /** * Looks up credible Records in the Cache (a wrapper around lookupRecords). * Unlike lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findRecords(Name name, short type) { return findRecords(name, type, Credibility.NONAUTH_ANSWER); } /** * Looks up Records in the Cache (a wrapper around lookupRecords). Unlike * lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findAnyRecords(Name name, short type) { return findRecords(name, type, Credibility.NONAUTH_ADDITIONAL); } private void verifyRecords(Cache tcache) { Iterator it; it = tcache.names(); while (it.hasNext()) { Name name = (Name) it.next(); TypeMap tm = tcache.findName(name); if (tm == null) continue; Object [] elements; elements = tm.getAll(); if (elements == null) continue; for (int i = 0; i < elements.length; i++) { Element element = (Element) elements[i]; RRset rrset = element.rrset; /* for now, ignore negative cache entries */ if (rrset == null) continue; if (verifier != null) rrset.setSecurity(verifier.verify(rrset, this)); if (rrset.getSecurity() < DNSSEC.Secure) continue; addSet(name, rrset.getType(), element); } } } private final byte getCred(Name recordName, Name queryName, short section, boolean isAuth) { byte cred; if (section == Section.ANSWER) { if (isAuth && recordName.equals(queryName)) cred = Credibility.AUTH_ANSWER; else if (isAuth) cred = Credibility.AUTH_NONAUTH_ANSWER; else cred = Credibility.NONAUTH_ANSWER; } else if (section == Section.AUTHORITY) { if (isAuth) cred = Credibility.AUTH_AUTHORITY; else cred = Credibility.NONAUTH_AUTHORITY; } else if (section == Section.ADDITIONAL) { if (isAuth) cred = Credibility.AUTH_ADDITIONAL; else cred = Credibility.NONAUTH_ADDITIONAL; } else throw new IllegalArgumentException("getCred: invalid section"); return cred; } /** * Adds all data from a Message into the Cache. Each record is added with * the appropriate credibility, and negative answers are cached as such. * @param in The Message to be added * @see Message */ public void addMessage(Message in) { boolean isAuth = in.getHeader().getFlag(Flags.AA); Name queryName = in.getQuestion().getName(); Name lookupName = queryName; short queryType = in.getQuestion().getType(); short queryClass = in.getQuestion().getDClass(); byte cred; short rcode = in.getHeader().getRcode(); boolean haveAnswer = false; Record [] answers, auth, addl; if (secure) { Cache c = new Cache(dclass); c.addMessage(in); verifyRecords(c); return; } if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) return; answers = in.getSectionArray(Section.ANSWER); while (!haveAnswer || queryType == Type.ANY) { boolean restart = false; for (int i = 0; i < answers.length; i++) { short type = answers[i].getType(); short rrtype = answers[i].getRRsetType(); Name name = answers[i].getName(); cred = getCred(name, queryName, Section.ANSWER, isAuth); if (type == Type.CNAME && name.equals(lookupName)) { addRecord(answers[i], cred, in); CNAMERecord cname = (CNAMERecord) answers[i]; lookupName = cname.getTarget(); restart = true; } else if (rrtype == Type.CNAME && name.equals(lookupName)) { addRecord(answers[i], cred, in); } else if (type == Type.DNAME && lookupName.subdomain(name)) { addRecord(answers[i], cred, in); DNAMERecord dname = (DNAMERecord) answers[i]; lookupName = lookupName.fromDNAME(dname); restart = true; } else if (rrtype == Type.DNAME && lookupName.subdomain(name)) { addRecord(answers[i], cred, in); } else if ((rrtype == queryType || queryType == Type.ANY) && name.equals(lookupName)) { addRecord(answers[i], cred, in); haveAnswer = true; } } if (!restart) break; } auth = in.getSectionArray(Section.AUTHORITY); if (!haveAnswer) { /* This is a negative response */ SOARecord soa = null; for (int i = 0; i < auth.length; i++) { if (auth[i].getType() == Type.SOA && lookupName.subdomain(auth[i].getName())) { soa = (SOARecord) auth[i]; break; } } if (soa != null) { /* This is a negative response. */ long soattl = (long)soa.getTTL() & 0xFFFFFFFFL; long soamin = (long)soa.getMinimum() & 0xFFFFFFFFL; long ttl = Math.min(soattl, soamin); if (maxncache >= 0) ttl = Math.min(ttl, maxncache); cred = getCred(soa.getName(), queryName, Section.AUTHORITY, isAuth); if (rcode == Rcode.NXDOMAIN) addNegative(rcode, lookupName, (short)0, ttl, cred, in); else addNegative(rcode, lookupName, queryType, ttl, cred, in); } } for (int i = 0; i < auth.length; i++) { short type = auth[i].getRRsetType(); Name name = auth[i].getName(); if ((type == Type.NS || type == Type.SOA) && lookupName.subdomain(name)) { cred = getCred(name, queryName, Section.AUTHORITY, isAuth); addRecord(auth[i], cred, in); } /* NXT records are not cached yet. */ } addl = in.getSectionArray(Section.ADDITIONAL); for (int i = 0; i < addl.length; i++) { short type = addl[i].getRRsetType(); if (type != Type.A && type != Type.AAAA && type != Type.A6) continue; /* XXX check the name */ Name name = addl[i].getName(); cred = getCred(name, queryName, Section.ADDITIONAL, isAuth); addRecord(addl[i], cred, in); } } /** * Flushes an RRset from the cache * @param name The name of the records to be flushed * @param type The type of the records to be flushed * @see RRset */ void flushSet(Name name, short type) { Element element = (Element) findExactSet(name, type); if (element == null || element.rrset == null) return; removeSet(name, type, element); } /** * Flushes all RRsets with a given name from the cache * @param name The name of the records to be flushed * @see RRset */ void flushName(Name name) { removeName(name); } /** * Defines a module to be used for data verification (DNSSEC). An * implementation is found in org.xbill.DNSSEC.security.DNSSECVerifier, * which requires Java 2 or above and the Java Cryptography Extensions. */ public void setVerifier(Verifier v) { verifier = v; } /** * Mandates that all data stored in this Cache must be verified and proven * to be secure, using a verifier (as defined in setVerifier). */ public void setSecurePolicy() { secure = true; } /** * Sets the maximum length of time that a negative response will be stored * in this Cache. A negative value disables this feature (that is, sets * no limit). */ public void setMaxNCache(int seconds) { maxncache = seconds; } /** * Sets the interval (in minutes) that all expired records will be expunged * the cache. The default is 30 minutes. 0 or a negative value disables this * feature. */ public void setCleanInterval(int minutes) { cleanInterval = minutes; if (cleanInterval <= 0) cleaner = null; else if (cleaner == null) cleaner = new CacheCleaner(); } }
package wyil.transforms; import java.util.*; import static wyil.util.SyntaxError.*; import static wyil.util.ErrorMessages.*; import wyc.stages.BackPropagation.Env; import wyil.ModuleLoader; import wyil.lang.Block; import wyil.lang.Code; import wyil.lang.Module; import wyil.lang.Type; import wyil.lang.Block.Entry; import wyil.util.Pair; import wyil.util.dfa.*; public class LiveVariablesAnalysis extends BackwardFlowAnalysis<LiveVariablesAnalysis.Env>{ private static final HashMap<Integer,Block.Entry> afterInserts = new HashMap<Integer,Block.Entry>(); private static final HashMap<Integer,Block.Entry> rewrites = new HashMap<Integer,Block.Entry>(); private static final HashSet<Integer> deadcode = new HashSet<Integer>(); public LiveVariablesAnalysis(ModuleLoader loader) { super(loader); } @Override public Module.TypeDef propagate(Module.TypeDef type) { // TODO: back propagate through type constraints return type; } /** * Last store for the live variables analysis is empty, because all * variables are considered to be dead at the end of a method/function. * * @return */ @Override public Env lastStore() { return EMPTY_ENV; } @Override public Module.Case propagate(Module.Case mcase) { // TODO: back propagate through pre- and post-conditions methodCase = mcase; stores = new HashMap<String,Env>(); afterInserts.clear(); rewrites.clear(); deadcode.clear(); Block body = mcase.body(); Env environment = lastStore(); propagate(0,body.size(), environment, Collections.EMPTY_LIST); // First, check and report any dead-code for(Integer i : deadcode) { syntaxError(errorMessage(DEAD_CODE), filename, body.get(i)); } // At this point, we apply the inserts Block nbody = new Block(body.numInputs()); for(int i=0;i!=body.size();++i) { Block.Entry rewrite = rewrites.get(i); if(rewrite != null) { nbody.append(rewrite); } else { nbody.append(body.get(i)); } Block.Entry afters = afterInserts.get(i); if(afters != null) { nbody.append(afters); } } return new Module.Case(nbody, mcase.precondition(), mcase.postcondition(), mcase.locals(), mcase.attributes()); } @Override public Env propagate(int index, Entry entry, Env environment) { Code code = entry.code; if(code instanceof Code.Load) { Code.Load load = (Code.Load) code; if(!environment.contains(load.slot)) { rewrites.put( index, new Block.Entry(Code.Move(load.type, load.slot), entry .attributes())); } else { rewrites.put(index, null); } environment = new Env(environment); environment.add(load.slot); } else if(code instanceof Code.Store) { Code.Store store = (Code.Store) code; // FIXME: should I report an error or warning here? // if(!environment.contains(store.slot)) { // deadcode.add(index); environment = new Env(environment); environment.remove(store.slot); } else if(code instanceof Code.Update) { Code.Update update = (Code.Update) code; if(update.beforeType instanceof Type.Process) { // updating a field on this constitutes a use environment = new Env(environment); environment.add(update.slot); } else if(!environment.contains(update.slot)) { deadcode.add(index); } else { deadcode.remove(index); } } return environment; } @Override public Env propagate(int index, Code.IfGoto igoto, Entry stmt, Env trueEnv, Env falseEnv) { return join(trueEnv,falseEnv); } @Override protected Env propagate(Type handler, Env normalEnv, Env exceptionEnv) { return join(normalEnv, exceptionEnv); } @Override public Env propagate(int index, Code.IfType code, Entry stmt, Env trueEnv, Env falseEnv) { Env r = join(trueEnv,falseEnv); if(code.slot >= 0) { r.add(code.slot); } return r; } @Override public Env propagate(int index, Code.Switch sw, Entry stmt, List<Env> environments, Env defEnv) { Env environment = defEnv; for(int i=0;i!=sw.branches.size();++i) { environment = join(environment,environments.get(i)); } return environment; } public Env propagate(int start, int end, Code.Loop loop, Entry stmt, Env environment, List<Pair<Type,String>> handlers) { Env oldEnv = null; Env newEnv = null; if(loop instanceof Code.ForAll) { environment = new Env(environment); } else { environment = EMPTY_ENV; } do { // iterate until a fixed point reached oldEnv = newEnv != null ? newEnv : environment; newEnv = propagate(start+1,end, oldEnv, handlers); } while (!newEnv.equals(oldEnv)); environment = newEnv; if(loop instanceof Code.ForAll) { Code.ForAll fall = (Code.ForAll) loop; // FIXME: is the following really necessary? environment.remove(fall.slot); } return environment; } private Env join(Env env1, Env env2) { // implements set union Env r = new Env(env1); r.addAll(env2); return r; } private static final Env EMPTY_ENV = new Env(); public static final class Env extends HashSet<Integer> { public Env() { super(); } public Env(Env env) { super(env); } } }
package org.wikipedia.page; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.graphics.Typeface; import android.util.SparseIntArray; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.getkeepsafe.taptargetview.TapTargetView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.ToCInteractionFunnel; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.settings.Prefs; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.L10nUtil; import org.wikipedia.util.StringUtil; import org.wikipedia.util.log.L; import org.wikipedia.views.ObservableWebView; import org.wikipedia.views.PageScrollerView; import org.wikipedia.views.SwipeableListView; import java.util.ArrayList; import static org.wikipedia.util.L10nUtil.getStringForArticleLanguage; import static org.wikipedia.util.L10nUtil.setConditionalLayoutDirection; import static org.wikipedia.util.ResourceUtil.getThemedColor; public class ToCHandler implements ObservableWebView.OnClickListener, ObservableWebView.OnScrollChangeListener, ObservableWebView.OnContentHeightChangedListener, ObservableWebView.OnEdgeSwipeListener{ private static final float SCROLLER_BUTTON_SIZE = 44f; private static final float SCROLLER_BUTTON_PEEK_MARGIN = -18f; private static final float SCROLLER_BUTTON_HIDE_MARGIN = 48f; private static final float SCROLLER_BUTTON_ONBOARDING_MARGIN = 22f; private static final float SCROLLER_BUTTON_REVEAL_MARGIN = -30f; private static final int SCROLLER_BUTTON_HIDE_TIMEOUT_MILLIS = 2000; private static final float TOC_LEAD_TEXT_SIZE = 24f; private static final float TOC_SECTION_TEXT_SIZE = 18f; private static final float TOC_SUBSECTION_TEXT_SIZE = 14f; private static final float TOC_SEMI_FADE_ALPHA = 0.9f; private static final float TOC_SECTION_TOP_OFFSET_ADJUST = 70f; private static final int MAX_LEVELS = 3; private static final int ABOUT_SECTION_ID = -1; private final SwipeableListView tocList; private final PageScrollerView scrollerView; private final FrameLayout.LayoutParams scrollerViewParams; private final ViewGroup tocContainer; private final ObservableWebView webView; private final CommunicationBridge bridge; private final PageFragment fragment; private ToCAdapter adapter = new ToCAdapter(); private ToCInteractionFunnel funnel; private boolean rtl; private boolean scrollerShown; private boolean tocShown; private boolean showOnboading; private int currentItemSelected; private Runnable hideScrollerRunnable = new Runnable() { @Override public void run() { if (!tocShown) { hideScroller(); } } }; ToCHandler(final PageFragment fragment, ViewGroup tocContainer, PageScrollerView scrollerView, final CommunicationBridge bridge) { this.fragment = fragment; this.bridge = bridge; this.tocContainer = tocContainer; this.scrollerView = scrollerView; scrollerViewParams = new FrameLayout.LayoutParams(DimenUtil.roundedDpToPx(SCROLLER_BUTTON_SIZE), DimenUtil.roundedDpToPx(SCROLLER_BUTTON_SIZE)); tocList = tocContainer.findViewById(R.id.toc_list); tocList.setAdapter(adapter); tocList.setOnItemClickListener((parent, view, position, id) -> { Section section = adapter.getItem(position); scrollToSection(section); funnel.logClick(); hide(); }); tocList.setListener(this::hide); webView = fragment.getWebView(); webView.addOnClickListener(this); webView.addOnScrollChangeListener(this); webView.addOnContentHeightChangedListener(this); webView.setOnEdgeSwipeListener(this); bridge.addListener("sectionDataResponse", (messageType, messagePayload) -> { try { JSONArray sections = messagePayload.getJSONArray("sections"); for (int i = 0; i < sections.length(); i++) { adapter.setYOffset(sections.getJSONObject(i).getInt("id"), sections.getJSONObject(i).getInt("yOffset")); } // artificially add height for bottom About section adapter.setYOffset(ABOUT_SECTION_ID, webView.getContentHeight() - (int)(fragment.getBottomContentView().getHeight() / DimenUtil.getDensityScalar())); } catch (JSONException e) { // ignore } }); scrollerView.setCallback(new ScrollerCallback()); setScrollerPosition(); // create a dummy funnel, in case the drawer is pulled out before a page is loaded. funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(), WikipediaApp.getInstance().getWikiSite(), 0, 0); } @SuppressLint("RtlHardcoded") void setupToC(@NonNull Page page, @NonNull WikiSite wiki, boolean firstPage) { adapter.setPage(page); rtl = L10nUtil.isLangRTL(wiki.languageCode()); showOnboading = Prefs.isTocTutorialEnabled() && !page.isMainPage() && !firstPage; tocList.setRtl(rtl); setConditionalLayoutDirection(tocContainer, wiki.languageCode()); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)tocContainer.getLayoutParams(); params.gravity = rtl ? Gravity.LEFT : Gravity.RIGHT; tocContainer.setLayoutParams(params); log(); funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(), wiki, page.getPageProperties().getPageId(), adapter.getCount()); } void log() { if (funnel != null) { funnel.log(); } } void scrollToSection(String sectionAnchor) { JSONObject payload = new JSONObject(); try { payload.put("anchor", sectionAnchor); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("scrollToSection", payload); } private void scrollToSection(Section section) { if (section != null) { // is it the bottom (about) section? if (section.getId() == ABOUT_SECTION_ID) { JSONObject payload = new JSONObject(); try { final int topPadding = 16; payload.put("offset", topPadding + (int) (fragment.getBottomContentView().getHeight() / DimenUtil.getDensityScalar())); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("scrollToBottom", payload); } else { scrollToSection(section.isLead() ? "heading_" + section.getId() : section.getAnchor()); } } } public void show() { fadeInToc(false); bringOutScroller(); } public void hide() { fadeOutToc(); bringInScroller(); } public boolean isVisible() { return tocShown; } public void setEnabled(boolean enabled) { if (enabled) { scrollerView.setTranslationX(DimenUtil.roundedDpToPx(rtl ? -SCROLLER_BUTTON_HIDE_MARGIN : SCROLLER_BUTTON_HIDE_MARGIN)); scrollerView.setVisibility(View.VISIBLE); setScrollerPosition(); if (showOnboading) { showTocOnboarding(); } } else { tocContainer.setVisibility(View.GONE); scrollerView.setVisibility(View.GONE); hideScroller(); } } @Override public boolean onClick(float x, float y) { if (isVisible()) { hide(); } else { showScrollerThenHide(); } return false; } @Override public void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll) { setScrollerPosition(); } @Override public void onContentHeightChanged(int contentHeight) { if (!fragment.isLoading()) { bridge.sendMessage("requestSectionData", new JSONObject()); } } @Override public void onEdgeSwipe(boolean direction) { if (direction == rtl) { show(); } } public final class ToCAdapter extends BaseAdapter { private final ArrayList<Section> sections = new ArrayList<>(); private final SparseIntArray sectionYOffsets = new SparseIntArray(); private String pageTitle; private int highlightedSection; void setPage(@NonNull Page page) { sections.clear(); sectionYOffsets.clear(); pageTitle = page.getDisplayTitle(); for (Section s : page.getSections()) { if (s.getLevel() < MAX_LEVELS) { sections.add(s); } } // add a fake section at the end to represent the "about this article" contents at the bottom: sections.add(new Section(ABOUT_SECTION_ID, 0, getStringForArticleLanguage(page.getTitle(), R.string.about_article_section), "", "")); highlightedSection = 0; notifyDataSetChanged(); } void setHighlightedSection(int id) { highlightedSection = id; notifyDataSetChanged(); } int getYOffset(int id) { return sectionYOffsets.get(id, 0); } void setYOffset(int id, int yOffset) { sectionYOffsets.put(id, yOffset); } @Override public int getCount() { return sections.size(); } @Override public Section getItem(int position) { return sections.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_toc_entry, parent, false); } Section section = getItem(position); TextView sectionHeading = convertView.findViewById(R.id.page_toc_item_text); View sectionBullet = convertView.findViewById(R.id.page_toc_item_bullet); sectionHeading.setText(StringUtil.fromHtml(section.isLead() ? pageTitle : section.getHeading())); float textSize = TOC_SUBSECTION_TEXT_SIZE; if (section.isLead()) { textSize = TOC_LEAD_TEXT_SIZE; sectionHeading.setTypeface(Typeface.SERIF); } else if (section.getLevel() == 1) { textSize = TOC_SECTION_TEXT_SIZE; sectionHeading.setTypeface(Typeface.SERIF); } else { sectionHeading.setTypeface(Typeface.SANS_SERIF); } sectionHeading.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) sectionBullet.getLayoutParams(); params.topMargin = DimenUtil.roundedDpToPx(textSize / 2); sectionBullet.setLayoutParams(params); if (highlightedSection == position) { sectionHeading.setTextColor(getThemedColor(fragment.requireContext(), R.attr.colorAccent)); } else { if (section.getLevel() > 1) { sectionHeading.setTextColor( getThemedColor(fragment.requireContext(), R.attr.primary_text_color)); } else { sectionHeading.setTextColor( getThemedColor(fragment.requireContext(), R.attr.toc_h1_h2_color)); } } return convertView; } } private void showTocOnboarding() { try { showScroller(); showCompleteScroller(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); FeedbackUtil.showTapTargetView(fragment.requireActivity(), scrollerView, R.string.tool_tip_toc_title, R.string.tool_tip_toc_text, new TapTargetView.Listener() { boolean targetClicked; @Override public void onTargetClick(TapTargetView view) { super.onTargetClick(view); targetClicked = true; show(); } @Override public void onTargetDismissed(TapTargetView view, boolean userInitiated) { if (!targetClicked) { hide(); } } }); } }); } catch (Exception e) { L.w("ToC onboarding failed", e); } Prefs.setTocTutorialEnabled(false); } @SuppressLint("RtlHardcoded") private void setScrollerPosition() { scrollerViewParams.gravity = rtl ? Gravity.LEFT : Gravity.RIGHT; scrollerViewParams.leftMargin = rtl ? DimenUtil.roundedDpToPx(SCROLLER_BUTTON_PEEK_MARGIN) : 0; scrollerViewParams.rightMargin = rtl ? 0 : DimenUtil.roundedDpToPx(SCROLLER_BUTTON_PEEK_MARGIN); int toolbarHeight = DimenUtil.getToolbarHeightPx(fragment.requireContext()); scrollerViewParams.topMargin = (int) (toolbarHeight + (webView.getHeight() - 2 * toolbarHeight) * ((float)webView.getScrollY() / (float)webView.getContentHeight() / DimenUtil.getDensityScalar())); if (scrollerViewParams.topMargin < toolbarHeight) { scrollerViewParams.topMargin = toolbarHeight; } scrollerView.setLayoutParams(scrollerViewParams); } private void fadeInToc(boolean semiFade) { tocContainer.setAlpha(tocShown ? 1f : 0f); tocContainer.setVisibility(View.VISIBLE); tocContainer.animate().alpha(semiFade ? TOC_SEMI_FADE_ALPHA : 1f) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(null); tocList.setEnabled(true); currentItemSelected = -1; onScrollerMoved(0f, false); funnel.scrollStart(); if (semiFade) { return; } tocShown = true; scrollerView.removeCallbacks(hideScrollerRunnable); } private void fadeOutToc() { tocContainer.animate().alpha(0f) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { tocContainer.setVisibility(View.GONE); } }); tocList.setEnabled(false); tocShown = false; funnel.scrollStop(); } private void bringOutScroller() { if (scrollerView.getVisibility() != View.VISIBLE) { return; } scrollerView.removeCallbacks(hideScrollerRunnable); scrollerView.animate().translationX(DimenUtil.roundedDpToPx(rtl ? -SCROLLER_BUTTON_REVEAL_MARGIN : SCROLLER_BUTTON_REVEAL_MARGIN)) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(null); scrollerShown = true; } private void bringInScroller() { if (scrollerView.getVisibility() != View.VISIBLE) { return; } scrollerView.removeCallbacks(hideScrollerRunnable); hideScroller(); } private void showScroller() { if (scrollerView.getVisibility() != View.VISIBLE) { return; } scrollerView.removeCallbacks(hideScrollerRunnable); scrollerView.animate().translationX(0) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(null); scrollerShown = true; funnel.peek(); } private void hideScroller() { scrollerShown = false; if (scrollerView.getVisibility() != View.VISIBLE) { return; } scrollerView.animate().translationX(DimenUtil.roundedDpToPx(rtl ? -SCROLLER_BUTTON_HIDE_MARGIN : SCROLLER_BUTTON_HIDE_MARGIN)) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(null); funnel.hide(); } private void showCompleteScroller(@Nullable AnimatorListenerAdapter listenerAdapter) { if (scrollerView.getVisibility() != View.VISIBLE) { return; } scrollerView.animate().translationX(DimenUtil.roundedDpToPx(rtl ? SCROLLER_BUTTON_ONBOARDING_MARGIN : -SCROLLER_BUTTON_ONBOARDING_MARGIN)) .setDuration(tocContainer.getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(listenerAdapter); } private void showScrollerThenHide() { if (!scrollerShown) { showScroller(); } scrollerView.removeCallbacks(hideScrollerRunnable); scrollerView.postDelayed(hideScrollerRunnable, SCROLLER_BUTTON_HIDE_TIMEOUT_MILLIS); } private void scrollToListSectionByOffset(int yOffset) { yOffset = DimenUtil.roundedPxToDp(yOffset); int itemToSelect = 0; for (int i = 1; i < adapter.getCount(); i++) { Section section = adapter.getItem(i); if (adapter.getYOffset(section.getId()) < yOffset) { itemToSelect = i; } else { break; } } if (itemToSelect != currentItemSelected) { adapter.setHighlightedSection(itemToSelect); currentItemSelected = itemToSelect; } tocList.smoothScrollToPositionFromTop(currentItemSelected, scrollerViewParams.topMargin - DimenUtil.roundedDpToPx(TOC_SECTION_TOP_OFFSET_ADJUST), 0); } private void onScrollerMoved(float dy, boolean scrollWebView) { int webViewScrollY = webView.getScrollY(); int webViewHeight = webView.getHeight(); float webViewContentHeight = webView.getContentHeight() * DimenUtil.getDensityScalar(); float scrollY = webViewScrollY; scrollY += (dy * webViewContentHeight / (float)(webViewHeight - 2 * DimenUtil.getToolbarHeightPx(fragment.requireContext()))); if (scrollY < 0) { scrollY = 0; } else if (scrollY > (webViewContentHeight - webViewHeight)) { scrollY = webViewContentHeight - webViewHeight; } if (scrollWebView) { webView.scrollTo(0, (int) scrollY); } scrollToListSectionByOffset((int) scrollY + webViewHeight / 2); } private class ScrollerCallback implements PageScrollerView.Callback { @Override public void onClick() { show(); } @Override public void onScrollStart() { fadeInToc(true); bringOutScroller(); } @Override public void onScrollStop() { fadeOutToc(); bringInScroller(); } @Override public void onVerticalScroll(float dy) { onScrollerMoved(dy, true); } @Override public void onSwipeOut() { fadeInToc(false); } } }
package soft.swenggroup5; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { /** * Constants * * WHITE: Hex value to colour generated qr code pixels white * BLACK: Hex value to colour generated qr code pixels black * WIDTH: The width of the generated qr code TODO include in layout to scale correctly? * HEIGHT: The height of the generated qr code TODO include in layout to scale correctly? * DEFAULT_STR: Test string to show generation of qr code TODO remove * INTEGRATOR: Object that is used to access the integrated scanner * TEST_FILE: test file to show encoding of header TODO remove */ private final static int WHITE = 0xFFFFFFFF; private final static int BLACK = 0xFF000000; private final static int WIDTH = 400; private final static int HEIGHT = 400; private final static String STR = "Software Engineering Group 5 - SOFT"; private final IntentIntegrator INTEGRATOR = new IntentIntegrator(this); private File TEST_FILE; private final static int MAX_FILE_SIZE = 2000; /** * onCreate * * TODO note that this is only for the base state of V1 * * Entry point for app when started. Initializes the generated qr code, the scan button, * and attaches a listener to the scan button. * * @param savedInstanceState: required param to instantiate the super class */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the scan button referencing the button in res/activity_main.xml Button scanButton = (Button)findViewById(R.id.button); // Create a space that will be used to present the demo generated qr code ImageView imageView = (ImageView) findViewById(R.id.qrCode); try { // cannot initialize as a constant as an error must be handled. // TODO move this to unit tests TEST_FILE = File.createTempFile("testing", ".txt"); // explicitly specify that the temp file is to be deleted on exit of the app TEST_FILE.deleteOnExit(); // write hello to the temp file FileOutputStream s = new FileOutputStream(TEST_FILE); s.write('h'); s.write('e'); s.write('l'); s.write('l'); s.write('o'); // close the stream s.close(); } catch (Exception e) { Log.d("Write_to_temp", e.toString()); } // Attempt to generate the qr code and put it into the ImageView try { List<Byte> Header = encodeHeader(TEST_FILE); Bitmap bitmap = encodeAsBitmap(STR); imageView.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } // Create the event listener for when scanButton is clicked scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * setDesiredBarcodeFormats: setting the scanner to scan qr codes, this can be * changed to scan other codes (bar codes) and may become useful if we want to * implement extended functionality beyond V1 * setPrompt: a string shown to the user when scanning. May make this dynamic * to show how many qr codes have been scanned so far (probably V1) * setCameraId: use a specific camera of the device (front or back) * setBeepEnabled: when true, audible beep occurs when scan occurs * setBarcodeImageEnabled: TODO investigate * initiateScan: open the scanner (after it has been configured) */ INTEGRATOR.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); INTEGRATOR.setPrompt("Scan the files qr code"); INTEGRATOR.setCameraId(0); INTEGRATOR.setBeepEnabled(false); INTEGRATOR.setBarcodeImageEnabled(true); INTEGRATOR.initiateScan(); } }); } /** * encodeAsBitmap * * Takes a string and returns a bitmap representation of the string as a qr code * * @param stringToConvert: the string to generate a qr code for * @return a bitmap representing the qr code generated for the passed string * @throws WriterException */ Bitmap encodeAsBitmap(String stringToConvert) throws WriterException { // TODO investigate BitMatrix result; try { result = new MultiFormatWriter().encode(stringToConvert, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, null); } catch (IllegalArgumentException iae) { // Unsupported format return null; } int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * encodeHeader * * Takes a file and its position and returns an ArrayList of bytes representing * 1. File size * 2. File Type * 3. Hash value * 4. Number of qr codes * * @param file: the data to be used * @return A List of bytes to be used as the QR code header */ List encodeHeader(File file) { ArrayList<String> headerString = new ArrayList<String>(); List<Byte> listOfBytes = new ArrayList<Byte>(); //FILE SIZE headerString.add(String.valueOf(file.length()+"|")); // FILE TYPE String filename = getMimeType(file); headerString.add(filename+"|"); // HASH VALUE int h = file.hashCode(); headerString.add(String.valueOf(h)+"|"); //NUMBER OF QR CODE int qrCodes = splitFileSize(headerString.size()+5); headerString.add(String.valueOf(qrCodes)); headerString.add(String.valueOf("\0")); //End tag for header for(int i = 0; i < headerString.size(); i++) { byte[] b = headerString.get(i).getBytes(); for(int j=0; j < b.length;j++) { listOfBytes.add(b[j]); } } for(int i =0; i<listOfBytes.size();i++) { // FOR DEBUGGING PURPOSES Log.d("Header val "+i,String.valueOf(listOfBytes.get(i))); } return listOfBytes; } public static String getMimeType(File file) { String filePath = file.getAbsolutePath(); Log.d("File_path", filePath); String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(filePath); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } Log.d("File_MIME_type", type); return type; } /** * splitFileSize * * Takes in a file size and calculates the number of QR codes needed to transfer it. * * @param size: the size of the file to be transferred. * @return the number of QR Codes required. */ public static int splitFileSize(int size) { if(size<=0) { return 0; } else { if(size%MAX_FILE_SIZE>0 || size<MAX_FILE_SIZE) { return size / MAX_FILE_SIZE + 1; } else { return size / MAX_FILE_SIZE; } } } /** * onActivityResult * * Defines what happens when a successful read of a qr code occurs. Right now (at base), when * a qr code is successfully scanned, the scanner is exited and the contents of the scan * are breifly shown on the device screen TODO update when changes * * @param requestCode: TODO investigate params * @param resultCode: TODO investigate params * @param data: TODO investigate params */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Log.d("Scan_Button", "Cancelled scan"); Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { Log.d("Scan_Button", "Scanned"); Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show(); } } else { // This is important, otherwise the result will not be passed to the fragment super.onActivityResult(requestCode, resultCode, data); } } }
package com.akjava.lib.common.param; public class ParameterUtils { public static Parameter parse(String line){ return parse(line,':'); } public static Parameter parse(String line,char separator){ int start=line.indexOf("("); if(start==-1){ return new Parameter(line); }else{ String name=line.substring(0,start); int end=line.lastIndexOf(")"); String inside; if(end==-1){ inside=line.substring(start+1); }else{ inside=line.substring(start+1,end); } Parameter p=new Parameter(name); if(inside.isEmpty()){ return p; } String[] atts=inside.split(""+separator); for(String at:atts){ p.add(at); } return p; } } }
package com.blarg.gdx.tilemap3d.prefabs; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.blarg.gdx.tilemap3d.Tile; import com.blarg.gdx.tilemap3d.TileContainer; public class TilePrefab extends TileContainer { public enum Rotation { ROT0(0), ROT90(90), ROT180(180), ROT270(270); int value; private Rotation(int value) { this.value = value; } public int value() { return value; } }; Tile[] data; int width; int height; int depth; final BoundingBox bounds = new BoundingBox(); final BoundingBox tmpBounds = new BoundingBox(); Rotation rotation; int rotationWidth; int rotationDepth; int rotationXOffset; int rotationZOffset; int rotationXMultiplier; int rotationZMultiplier; int rotationXPreMultiplier; int rotationZPreMultiplier; final BoundingBox rotationBounds = new BoundingBox(); final BoundingBox tmpRotationBounds = new BoundingBox(); @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } @Override public int getDepth() { return depth; } @Override public int getMinX() { return 0; } @Override public int getMinY() { return 0; } @Override public int getMinZ() { return 0; } @Override public int getMaxX() { return width - 1; } @Override public int getMaxY() { return height - 1; } @Override public int getMaxZ() { return depth - 1; } @Override public BoundingBox getBounds() { tmpBounds.set(bounds); return tmpBounds; } @Override public Vector3 getPosition() { return null; } public Rotation getRotation() { return rotation; } public int getRotationAngle() { return rotation.value; } public int getRotatedWidth() { return rotationWidth; } public int getRotatedDepth() { return rotationDepth; } public BoundingBox getRotatedBounds() { tmpRotationBounds.set(rotationBounds); return tmpRotationBounds; } public TilePrefab(int width, int height, int depth) { this.width = width; this.height = height; this.depth = depth; bounds.min.set(Vector3.Zero); bounds.max.set(width, height, depth); int numTiles = width * height * depth; data = new Tile[numTiles]; for (int i = 0; i < numTiles; ++i) data[i] = new Tile(); rotate(Rotation.ROT0); } @Override public Tile get(int x, int y, int z) { int index = getIndexOf(x, y, z); return data[index]; } @Override public Tile getSafe(int x, int y, int z) { if (!isWithinLocalBounds(x, y, z)) return null; else return get(x, y, z); } public void rotate(Rotation rotation) { this.rotation = rotation; switch (rotation) { case ROT0: rotationWidth = width; rotationDepth = depth; rotationXOffset = 0; rotationZOffset = 0; rotationXMultiplier = 1; rotationZMultiplier = rotationWidth; rotationXPreMultiplier = 1; rotationZPreMultiplier = 1; rotationBounds.min.set(Vector3.Zero); rotationBounds.max.set(rotationWidth, height, rotationDepth); break; case ROT90: rotationWidth = depth; rotationDepth = width; rotationXOffset = rotationWidth - 1; rotationZOffset = 0; rotationXMultiplier = rotationDepth; rotationZMultiplier = 1; rotationXPreMultiplier = -1; rotationZPreMultiplier = 1; rotationBounds.min.set(Vector3.Zero); rotationBounds.max.set(rotationWidth, height, rotationDepth); break; case ROT180: rotationWidth = width; rotationDepth = depth; rotationXOffset = rotationWidth - 1; rotationZOffset = rotationDepth - 1; rotationXMultiplier = 1; rotationZMultiplier = rotationWidth; rotationXPreMultiplier = -1; rotationZPreMultiplier = -1; rotationBounds.min.set(Vector3.Zero); rotationBounds.max.set(rotationWidth, height, rotationDepth); break; case ROT270: rotationWidth = depth; rotationDepth = width; rotationXOffset = 0; rotationZOffset = rotationDepth - 1; rotationXMultiplier = rotationDepth; rotationZMultiplier = 1; rotationXPreMultiplier = 1; rotationZPreMultiplier = -1; rotationBounds.min.set(Vector3.Zero); rotationBounds.max.set(rotationWidth, height, rotationDepth); break; } } public Tile getWithRotation(int x, int y, int z) { int index = getIndexOfWithRotation(x, y, z); return data[index]; } public void placeIn(TileContainer destination, int minX, int minY, int minZ, Rotation rotation, boolean copyEmptyTiles) { if (destination == null) throw new IllegalArgumentException(); if (!this.rotation.equals(rotation)) rotate(rotation); if (!((minX + rotationWidth) < destination.getWidth())) throw new RuntimeException("Destination not large enough."); if (!((minY + height) < destination.getHeight())) throw new RuntimeException("Destination not large enough."); if (!((minZ + rotationDepth) < destination.getDepth())) throw new RuntimeException("Destination not large enough."); for (int y = 0; y < height; ++y) { for (int z = 0; z < rotationDepth; ++z) { for (int x = 0; x < rotationWidth; ++x) { Tile sourceTile = getWithRotation(x, y, z); if (!copyEmptyTiles && sourceTile.isEmptySpace()) continue; Tile destTile = destination.get(minX + x, minY + y, minZ + z); destTile.set(sourceTile); } } } } private int getIndexOf(int x, int y, int z) { return (y * width * depth) + (z * width) + x; } private int getIndexOfWithRotation(int x, int y, int z) { return (y * rotationWidth * rotationDepth) + ((rotationZPreMultiplier * z + rotationZOffset) * rotationZMultiplier) + ((rotationXPreMultiplier * x + rotationXOffset) * rotationXMultiplier); } }
package com.brein.time.timeseries; import com.brein.time.exceptions.IllegalConfiguration; import com.brein.time.exceptions.IllegalTimePoint; import com.brein.time.exceptions.IllegalTimePointIndex; import com.brein.time.exceptions.IllegalTimePointMovement; import com.brein.time.exceptions.IllegalValueRegardingConfiguration; import java.io.Serializable; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; import java.util.function.Function; public class BucketTimeSeries<T extends Serializable> implements Iterable<T>, Serializable { private static final long serialVersionUID = 1L; protected final BucketTimeSeriesConfig<T> config; protected T[] timeSeries = null; protected BucketEndPoints now = null; protected int currentNowIdx = -1; public BucketTimeSeries(final BucketTimeSeriesConfig<T> config) { this.config = config; this.timeSeries = createEmptyArray(); } /** * Constructor to create a pre-set time series. * * @param config the configuration to use * @param timeSeries the initiale time series * @param now the current now timestamp */ public BucketTimeSeries(final BucketTimeSeriesConfig<T> config, final T[] timeSeries, final long now) throws IllegalValueRegardingConfiguration { this.config = config; this.timeSeries = timeSeries; this.now = normalizeUnixTimeStamp(now); this.currentNowIdx = 0; if (this.timeSeries != null && this.timeSeries.length != config.getTimeSeriesSize()) { throw new IllegalValueRegardingConfiguration("The defined size of the time-series does not satisfy the " + "configured time-series size (" + this.timeSeries.length + " vs. " + config .getTimeSeriesSize() + ")."); } } @SuppressWarnings("unchecked") protected T[] createEmptyArray() { final T[] array = (T[]) Array.newInstance(config.getBucketContent(), config.getTimeSeriesSize()); if (applyZero()) { Arrays.fill(array, 0, array.length, zero()); } return array; } protected boolean applyZero() { return config.isFillNumberWithZero() && Number.class.isAssignableFrom(config.getBucketContent()); } /** * Resets the values from [fromIndex, endIndex). * * @param fromIndex the index to start from (included) * @param endIndex the index to end (excluded) */ protected void fill(int fromIndex, int endIndex) { fromIndex = fromIndex == -1 ? 0 : fromIndex; endIndex = endIndex == -1 || endIndex > this.timeSeries.length ? this.timeSeries.length : endIndex; if (applyZero()) { Arrays.fill(this.timeSeries, fromIndex, endIndex, zero()); } else { Arrays.fill(this.timeSeries, fromIndex, endIndex, null); } } public T[] getTimeSeries() { return timeSeries; } @SuppressWarnings("unchecked") public T[] order() { final T[] result; if (this.timeSeries != null && this.currentNowIdx != -1) { result = (T[]) Array.newInstance(config.getBucketContent(), config.getTimeSeriesSize()); final AtomicInteger i = new AtomicInteger(0); forEach(val -> result[i.getAndIncrement()] = val); } else { result = createEmptyArray(); } return result; } public long[] create(final Function<T, Long> supplier) { final long[] result = new long[config.getTimeSeriesSize()]; if (this.timeSeries != null && this.currentNowIdx != -1) { final AtomicInteger i = new AtomicInteger(0); forEach(val -> result[i.getAndIncrement()] = supplier.apply(val)); } else { final boolean applyZero = applyZero(); // just assume we have nulls everywhere for (int i = 0; i < result.length; i++) { if (applyZero) { result[i] = supplier.apply(zero()); } else { result[i] = supplier.apply(null); } } } return result; } public int getNowIdx() { return currentNowIdx; } /** * This method returns the value from the time-series as if it would be ordered (i.e., zero is now, 1 is the * previous moment, ...). * * @param idx the zero based index * * @return the value associated to the zero based index */ public T getFromZeroBasedIdx(final int idx) { if (this.timeSeries != null && this.currentNowIdx != -1) { // we can use the default validation, because the index still must be in the borders of the time-series validateIdx(idx); return get(idx(currentNowIdx + idx)); } else { return null; } } public BucketEndPoints getEndPoints(final int bucketsFromNow) throws IllegalTimePoint { if (currentNowIdx == -1 || now == null) { throw new IllegalTimePoint("The now is not set yet, thus no end-points can be returned"); } return now.move(bucketsFromNow); } public void set(final long unixTimeStamp, final T value) { final int idx = handleDataUnixTimeStamp(unixTimeStamp); if (idx == -1) { return; } set(idx, value); } public void modify(final long unixTimeStamp, final Function<T, T> mod) { final int idx = handleDataUnixTimeStamp(unixTimeStamp); if (idx == -1) { return; } modify(idx, mod); } public void modify(final int idx, final Function<T, T> mod) { set(idx, mod.apply(get(idx))); } public void set(final int idx, final T value) throws IllegalTimePointIndex { validateIdx(idx); this.timeSeries[idx] = value; } /** * Gets the value for the specified {@code idx}. * * @param idx the index of the bucket to get the current value for; must be a valid index * * @return the current value for selected bucket * * @see #getNowIdx() */ public T get(final int idx) { validateIdx(idx); return this.timeSeries[idx]; } /** * Determines the number of buckets used to cover the seconds. * * @param diffInSeconds the difference in seconds * * @return the amount of buckets used to cover this amount */ public int getBucketSize(final long diffInSeconds) { // convert one unit of this into seconds final long secondsPerBucket = TimeUnit.SECONDS.convert(config.getBucketSize(), config.getTimeUnit()); return (int) Math.ceil((double) diffInSeconds / secondsPerBucket); } protected int handleDataUnixTimeStamp(final long unixTimeStamp) { // first we have to determine the bucket (idx) final BucketEndPoints bucketEndPoints = normalizeUnixTimeStamp(unixTimeStamp); final long diff; if (this.now == null) { setNow(unixTimeStamp); diff = 0L; } else { diff = this.now.diff(bucketEndPoints); } // we are in the future, let's move there and set it if (diff > 0) { setNow(unixTimeStamp); return currentNowIdx; } // if we are outside the time, just ignore it else if (Math.abs(diff) >= config.getTimeSeriesSize()) { // do nothing return -1; } // the absolute index has to be made relative (idx(..)) else { return idx(currentNowIdx - diff); } } protected void validateIdx(final int idx) throws IllegalTimePointIndex { if (idx < 0 || idx >= config.getTimeSeriesSize()) { throw new IllegalTimePointIndex(String.format("The index %d is out of bound [%d, %d].", idx, 0, config .getTimeSeriesSize() - 1)); } } protected int idx(final long absIdx) { /* * The absolute index has to be mapped to a real array index. This is done * by using the modulo operation. Nevertheless, the module has a range of * -1 * config.getTimeSeriesSize() to config.getTimeSeriesSize(). Thus, * if negative we have to add the config.getTimeSeriesSize() once. */ final int idx = (int) (absIdx % config.getTimeSeriesSize()); return idx < 0 ? idx + config.getTimeSeriesSize() : idx; } /** * This method is used to determine the bucket the {@code unixTimeStamp} belongs into. The bucket is represented by * a {@link BucketEndPoints} instance, which defines the end-points of the bucket and provides methods to calculate * the distance between buckets. * * @param unixTimeStamp the time-stamp to determine the bucket for * * @return the bucket for the specified {@code unixTimeStamp} based on the configuration of the time-series */ public BucketEndPoints normalizeUnixTimeStamp(final long unixTimeStamp) { final TimeUnit timeUnit = config.getTimeUnit(); // first get the time stamp in the unit of the time-series final long timeStamp = timeUnit.convert(unixTimeStamp, TimeUnit.SECONDS); /* * Now lets, normalize the time stamp regarding to the bucketSize: * 1.) we need the size of a bucket * 2.) we need where the current time stamp is located within the size, * i.e., how much it reaches into the bucket (ratio => offset) * 3.) we use the calculated offset to determine the end points (in seconds) * * Example: * The time stamp 1002 (in minutes or seconds or ...?) should be mapped * to a normalized bucket, so the bucket would be, e.g., [1000, 1005). */ final int bucketSize = config.getBucketSize(); final long offset = timeStamp % bucketSize; final long start = timeStamp - offset; final long end = start + config.getBucketSize(); return new BucketEndPoints(TimeUnit.SECONDS.convert(start, timeUnit), TimeUnit.SECONDS.convert(end, timeUnit)); } @SuppressWarnings("unchecked") protected T zero() { final Class<?> contentType = config.getBucketContent(); if (Number.class.isAssignableFrom(contentType)) { if (Byte.class.equals(contentType)) { return (T) Byte.valueOf((byte) 0); } else if (Short.class.equals(contentType)) { return (T) Short.valueOf((short) 0); } else if (Integer.class.equals(contentType)) { return (T) Integer.valueOf(0); } else if (Long.class.equals(contentType)) { return (T) Long.valueOf(0L); } else if (Double.class.equals(contentType)) { return (T) Double.valueOf(0.0); } else if (Float.class.equals(contentType)) { return (T) Float.valueOf(0.0f); } else if (BigDecimal.class.equals(contentType)) { return (T) BigDecimal.valueOf(0); } else if (BigInteger.class.equals(contentType)) { return (T) BigInteger.valueOf(0); } else if (AtomicInteger.class.equals(contentType)) { return (T) new AtomicInteger(0); } else if (AtomicLong.class.equals(contentType)) { return (T) new AtomicLong(0); } else { return null; } } else { return null; } } public BucketTimeSeriesConfig<T> getConfig() { return config; } @Override public Iterator<T> iterator() { return new Iterator<T>() { final int currentIdx = getNowIdx(); final int size = BucketTimeSeries.this.config.getTimeSeriesSize(); int offset = 0; @Override public boolean hasNext() { return offset < size; } @Override public T next() { if (hasNext()) { final int idx = BucketTimeSeries.this.idx((long) currentIdx + offset); offset++; return BucketTimeSeries.this.timeSeries[idx]; } else { throw new NoSuchElementException("No further elements available."); } } }; } public long getNow() { if (now == null) { return -1L; } else { return now.getUnixTimeStampEnd() - 1; } } public void setNow(final long unixTimeStamp) throws IllegalTimePointMovement { /* * "now" strongly depends on the TimeUnit used for the timeSeries, as * well as the bucketSize. If, e.g., the TimeUnit is MINUTES and the * bucketSize is 5, a unix time stamp representing 01/20/1981 08:07:30 * must be mapped to 01/20/1981 08:10:00 (the next valid bucket). */ if (this.currentNowIdx == -1 || this.now == null) { this.currentNowIdx = 0; this.now = normalizeUnixTimeStamp(unixTimeStamp); } else { final BucketEndPoints newNow = normalizeUnixTimeStamp(unixTimeStamp); final long diff = this.now.diff(newNow); if (diff < 0) { throw new IllegalTimePointMovement(String.format("Cannot move to the past (current: %s, update: %s)", this.now, newNow)); } else if (diff > 0) { final int newCurrentNowIdx = idx(currentNowIdx - diff); /* * Remove the "passed" information. There are several things we have to * consider: * 1.) the whole array has to be reset * 2.) the array has to be reset partly forward * 3.) the array has to be reset "around the corner" */ if (diff >= config.getTimeSeriesSize()) { fill(-1, -1); } else if (newCurrentNowIdx > currentNowIdx) { fill(0, currentNowIdx); fill(newCurrentNowIdx, -1); } else { fill(newCurrentNowIdx, currentNowIdx); } // set the values calculated this.currentNowIdx = newCurrentNowIdx; this.now = newNow; } } } public void setTimeSeries(final T[] timeSeries, final long now) { this.now = normalizeUnixTimeStamp(now); this.currentNowIdx = 0; this.timeSeries = timeSeries; } public void combine(final BucketTimeSeries<T> timeSeries) throws IllegalConfiguration { combine(timeSeries, this::addition); } public void combine(final BucketTimeSeries<T> timeSeries, final BiFunction<T, T, T> cmb) throws IllegalConfiguration { final BucketTimeSeries<T> syncedTs = sync(timeSeries, ts -> new BucketTimeSeries<>(ts.getConfig(), ts.timeSeries, ts.getNow())); for (int i = 0; i < config.getTimeSeriesSize(); i++) { final int idx = idx(currentNowIdx + i); set(idx, cmb.apply(get(idx), syncedTs.get(syncedTs.idx(syncedTs.currentNowIdx + i)))); } } protected <B extends BucketTimeSeries<T>> B sync(final B timeSeries, final Function<B, B> copy) throws IllegalConfiguration { if (!Objects.equals(timeSeries.config, config)) { throw new IllegalConfiguration("The time-series to combine must have the same configuration."); } final int cmp = Long.compare(getNow(), timeSeries.getNow()); final B ts; if (cmp != 0 && getNow() == -1) { ts = timeSeries; setNow(timeSeries.getNow()); } else if (cmp != 0 && timeSeries.getNow() == -1) { ts = timeSeries; } else { if (cmp == 0) { ts = timeSeries; } else if (cmp > 0) { // the passed time-series is in the past ts = copy.apply(timeSeries); ts.setNow(this.getNow()); } else { // the passed time-series is in the future this.setNow(timeSeries.getNow()); ts = timeSeries; } } return ts; } @Override public String toString() { return Arrays.toString(order()); } @SuppressWarnings("unchecked") public T addition(final T a, final T b) { if (a == null && b == null) { return null; } else if (a == null) { return addition(zero(), b); } else if (b == null) { return addition(a, zero()); } final Class<T> contentType = (Class<T>) a.getClass(); if (Number.class.isAssignableFrom(contentType)) { if (Byte.class.equals(contentType)) { return (T) Byte.valueOf(Integer.valueOf(Byte.class.cast(a) + Byte.class.cast(b)).byteValue()); } else if (Short.class.equals(contentType)) { return (T) Short.valueOf(Integer.valueOf(Short.class.cast(a) + Short.class.cast(b)).shortValue()); } else if (Integer.class.equals(contentType)) { return (T) Integer.valueOf(Integer.class.cast(a) + Integer.class.cast(b)); } else if (Long.class.equals(contentType)) { return (T) Long.valueOf(Long.class.cast(a) + Long.class.cast(b)); } else if (Double.class.equals(contentType)) { return (T) Double.valueOf(Double.class.cast(a) + Double.class.cast(b)); } else if (Float.class.equals(contentType)) { return (T) Float.valueOf(Float.class.cast(a) + Float.class.cast(b)); } else if (BigDecimal.class.equals(contentType)) { return (T) BigDecimal.class.cast(a).add(BigDecimal.class.cast(b)); } else if (BigInteger.class.equals(contentType)) { return (T) BigInteger.class.cast(a).add(BigInteger.class.cast(b)); } else if (AtomicInteger.class.equals(contentType)) { final int intA = AtomicInteger.class.cast(a).intValue(); final int intB = AtomicInteger.class.cast(b).intValue(); return (T) new AtomicInteger(intA + intB); } else if (AtomicLong.class.equals(contentType)) { final long longA = AtomicLong.class.cast(a).longValue(); final long longB = AtomicLong.class.cast(b).longValue(); return (T) new AtomicLong(longA + longB); } else { return null; } } else if (String.class.isAssignableFrom(contentType)) { return (T) (String.class.cast(a) + String.class.cast(b)); } else if (List.class.isAssignableFrom(contentType)) { final List<T> list = new ArrayList<>(); list.addAll(List.class.cast(a)); list.addAll(List.class.cast(b)); return (T) list; } else if (Set.class.isAssignableFrom(contentType)) { final Set<T> set = new HashSet<>(); set.addAll(Set.class.cast(a)); set.addAll(Set.class.cast(b)); return (T) set; } else { return null; } } public long sumTimeSeries() { long totalSum = 0; for (final T i : this.timeSeries) { totalSum += ((Number) i).longValue(); } return totalSum; } }
package kbasesearchengine.search; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.LinkedList; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import com.google.common.base.Optional; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import kbasesearchengine.common.GUID; import kbasesearchengine.events.handler.SourceData; import kbasesearchengine.parse.ParsedObject; import kbasesearchengine.system.IndexingRules; import kbasesearchengine.system.ObjectTypeParsingRules; import kbasesearchengine.system.SearchObjectType; import kbasesearchengine.tools.Utils; import us.kbase.common.service.UObject; //TODO CODE remove 'fake' group IDs (-1 public, -2 admin). use alternate mechanism. public class ElasticIndexingStorage implements IndexingStorage { private static final String SUBTYPE_INDEX_SUFFIX = "_sub"; private static final String EXCLUDE_SUB_OJBS_URL_SUFFIX = ",-*" + SUBTYPE_INDEX_SUFFIX; private static final String OBJ_GUID = "guid"; private static final String OBJ_TIMESTAMP = "timestamp"; private static final String OBJ_PROV_COMMIT_HASH = "prv_cmt"; private static final String OBJ_PROV_MODULE_VERSION = "prv_ver"; private static final String OBJ_PROV_METHOD = "prv_meth"; private static final String OBJ_PROV_MODULE = "prv_mod"; private static final String OBJ_MD5 = "md5"; private static final String OBJ_COPIER = "copier"; private static final String OBJ_CREATOR = "creator"; private static final String OBJ_NAME = "oname"; private static final String OBJ_PREFIX = "prefix"; private static final String OBJ_STORAGE_CODE = "str_cde"; private static final String OBJ_ACCESS_GROUP_ID = "accgrp"; private static final String OBJ_VERSION = "version"; private static final String OBJ_IS_LAST = "islast"; private static final String OBJ_PUBLIC = "public"; private static final String OBJ_SHARED = "shared"; // tags on the data originating at the source of the data private static final String SOURCE_TAGS = "stags"; private static final String SEARCH_OBJ_TYPE = "otype"; private static final String SEARCH_OBJ_TYPE_VER = "otypever"; //readable names private static final String R_OBJ_GUID = "guid"; private static final String R_OBJ_TIMESTAMP = "timestamp"; private static final String R_OBJ_PROV_COMMIT_HASH = "provenance_commit"; private static final String R_OBJ_PROV_MODULE_VERSION = "provenance_module_ver"; private static final String R_OBJ_PROV_METHOD = "provenance_method"; private static final String R_OBJ_PROV_MODULE = "provenance_module"; private static final String R_OBJ_MD5 = "md5"; private static final String R_OBJ_COPIER = "copier"; private static final String R_OBJ_CREATOR = "creator"; private static final String R_OBJ_NAME = "object_name"; private static final String R_OBJ_PREFIX = "guid_prefix"; private static final String R_OBJ_STORAGE_CODE = "storage_code"; private static final String R_OBJ_ACCESS_GROUP_ID = "access_group_id"; private static final String R_OBJ_VERSION = "version"; private static final String R_OBJ_IS_LAST = "is_last_version"; private static final String R_OBJ_PUBLIC = "is_public"; private static final String R_OBJ_SHARED = "is_shared"; // tags on the data originating at the source of the data private static final String R_SOURCE_TAGS = "source_tags"; private static final String R_SEARCH_OBJ_TYPE = "type"; private static final String R_SEARCH_OBJ_TYPE_VER = "type_ver"; private static final ImmutableBiMap<String, String> READABLE_NAMES = ImmutableBiMap. <String,String>builder() .put(OBJ_GUID, R_OBJ_GUID) .put(OBJ_TIMESTAMP, R_OBJ_TIMESTAMP) .put(OBJ_PROV_COMMIT_HASH, R_OBJ_PROV_COMMIT_HASH) .put(OBJ_PROV_MODULE_VERSION, R_OBJ_PROV_MODULE_VERSION) .put(OBJ_PROV_METHOD, R_OBJ_PROV_METHOD) .put(OBJ_PROV_MODULE, R_OBJ_PROV_MODULE) .put(OBJ_MD5, R_OBJ_MD5) .put(OBJ_COPIER, R_OBJ_COPIER) .put(OBJ_CREATOR, R_OBJ_CREATOR) .put(OBJ_NAME, R_OBJ_NAME) .put(SOURCE_TAGS, R_SOURCE_TAGS) .put(SEARCH_OBJ_TYPE, R_SEARCH_OBJ_TYPE) .put(SEARCH_OBJ_TYPE_VER, R_SEARCH_OBJ_TYPE_VER) .put(OBJ_PREFIX, R_OBJ_PREFIX) .put(OBJ_STORAGE_CODE, R_OBJ_STORAGE_CODE) .put(OBJ_ACCESS_GROUP_ID, R_OBJ_ACCESS_GROUP_ID) .put(OBJ_VERSION, R_OBJ_VERSION) .put(OBJ_IS_LAST, R_OBJ_IS_LAST) .put(OBJ_PUBLIC, R_OBJ_PUBLIC) .put(OBJ_SHARED, R_OBJ_SHARED) .build(); private HttpHost esHost; private String esUser; private String esPassword; private String indexNamePrefix; private Map<ObjectTypeParsingRules, String> ruleToIndex = new LinkedHashMap<>(); private Map<String, String> typeToIndex = new LinkedHashMap<>(); private RestClient restClient = null; private File tempDir; public static final int PUBLIC_ACCESS_GROUP = -1; public static final int ADMIN_ACCESS_GROUP = -2; /** Maximum number of types that can be fit into the ElasticSearch HTTP URL max * length of 4kb (default). * i.e., MAX_OBJECT_TYPES_SIZE * {@link SearchObjectType#MAX_TYPE_SIZE} << URL length * giving us room for other url attribs like blacklists and subtype search filtering. * * This value is also reflected in the limit specified for SearchObjectsInput.object_types in * KBaseSearchEngine.spec. * */ public static final int MAX_OBJECT_TYPES_SIZE = 50; public ElasticIndexingStorage(HttpHost esHost, File tempDir) throws IOException { this.esHost = esHost; this.indexNamePrefix = ""; this.tempDir = tempDir; } public HttpHost getEsHost() { return esHost; } public File getTempDir() { return tempDir; } public String getEsUser() { return esUser; } public void setEsUser(String esUser) { this.esUser = esUser; } public void setEsPassword(String esPassword) { this.esPassword = esPassword; } public String getIndexNamePrefix() { return indexNamePrefix; } public void setIndexNamePrefix(String indexNamePrefix) { this.indexNamePrefix = indexNamePrefix; } private String getAnyIndexPattern() { return indexNamePrefix + "*"; } public void dropData() throws IOException { for (String indexName : listIndeces()) { if (indexName.startsWith(indexNamePrefix)) { deleteIndex(indexName); } } typeToIndex.clear(); ruleToIndex.clear(); } /** The specified list is valid if it, * * 1. is empty, * 2. or contains one or more non-null elements and size is less than * {@link ElasticIndexingStorage#MAX_OBJECT_TYPES_SIZE}. * * list 1 represents a list that would map to any index pattern (search unconstrained by type) * list 2 represents a list that would map to one or more specific index patterns (constrained search) * * * @param objectTypes a list of object types. * @throws IOException if list is invalid. */ private void validateObjectTypes(List<String> objectTypes) throws IOException { if (objectTypes == null) { throw new IllegalArgumentException("Invalid list of object types. List is null."); } if (objectTypes.isEmpty()) { return; } if (objectTypes.size() > MAX_OBJECT_TYPES_SIZE) { throw new IOException("Invalid list of object types. " + "List size exceeds maximum limit of " + MAX_OBJECT_TYPES_SIZE); } if (objectTypes.contains(null)) { throw new IOException("Invalid list of object types. Contains one or more null elements."); } } /** checks that at least one index exists for a type, and throws an exception otherwise. * * @param objectType * @return an index string that matches any version of the type. * @throws IOException */ private String checkIndex(final String objectType) throws IOException { String ret = typeToIndex.get(objectType); if (ret == null) { ensureAtLeastOneIndexExists(objectType); ret = getAnyTypePattern(objectType); typeToIndex.put(objectType, ret); } return ret; } private void ensureAtLeastOneIndexExists(final String objectType) throws IOException { //TODO VERS need to check there aren't duplicate type names based on case final String prefix = (indexNamePrefix + objectType + "_").toLowerCase(); for (final String index: listIndeces()) { if (index.startsWith(prefix)) { return; } } throw new IOException("No indexes exist for search type " + objectType); } private String getAnyTypePattern(final String objectType) { return (indexNamePrefix + objectType + "_*").toLowerCase(); } /* checks that an index exists for a specific version of a type. If the index * does not exist and noCreate is false, creates the index. * * Returns the elastic search index name. */ private String checkIndex( final ObjectTypeParsingRules rule, final boolean noCreate) throws IOException { Utils.nonNull(rule, "rule"); String ret = ruleToIndex.get(rule); if (ret == null) { ret = toIndexString(rule); if (!listIndeces().contains(ret)) { if (!noCreate) { System.out.println("Creating Elasticsearch index: " + ret); createTables(ret, rule.getIndexingRules()); } } ruleToIndex.put(rule, ret); } return ret; } private String toIndexString(final ObjectTypeParsingRules rule) { final SearchObjectType objectType = rule.getGlobalObjectType(); return (indexNamePrefix + objectType.getType() + "_" + objectType.getVersion() + (rule.getSubObjectType().isPresent() ? SUBTYPE_INDEX_SUFFIX : "")) .toLowerCase(); } @Override public void indexObject( final ObjectTypeParsingRules rule, final SourceData data, final Instant timestamp, final String parentJsonValue, final GUID id, final ParsedObject obj, final boolean isPublic) throws IOException, IndexingConflictException { final GUID parentID = new GUID(id, null, null); indexObjects(rule, data, timestamp, parentJsonValue, parentID, ImmutableMap.of(id, obj), isPublic); } // TODO CODE this function should just take a class rather than a zillion arguments // the class should ensure consistency of the various fields // IO exceptions are thrown for failure on creating or writing to file or contacting ES. @Override public void indexObjects( final ObjectTypeParsingRules rule, final SourceData data, final Instant timestamp, final String parentJsonValue, final GUID pguid, final Map<GUID, ParsedObject> idToObj, final boolean isPublic) throws IOException, IndexingConflictException { final Map<GUID, ParsedObject> idToObjCopy = new HashMap<>(idToObj); String indexName = checkIndex(rule, false); for (GUID id : idToObjCopy.keySet()) { GUID parentGuid = new GUID(id.getStorageCode(), id.getAccessGroupId(), id.getAccessGroupObjectId(), id.getVersion(), null, null); if (!parentGuid.equals(pguid)) { throw new IllegalStateException("Object GUID doesn't match parent GUID"); } } //TODO CODE if there's only a few objects to index, possible speed up by not using tempfile and just making direct API calls File tempFile = File.createTempFile("es_bulk_", ".json", tempDir); try { PrintWriter pw = new PrintWriter(tempFile); int lastVersion = loadLastVersion(indexName, pguid, pguid.getVersion()); final String esParentId = checkParentDoc(indexName, new LinkedHashSet<>( Arrays.asList(pguid)), isPublic, lastVersion).get(pguid); if (idToObjCopy.isEmpty()) { // there were no search objects parsed from the source object, so just index // the general object information idToObjCopy.put(pguid, null); } Map<GUID, String> esIds = lookupDocIds(indexName, idToObjCopy.keySet()); for (GUID id : idToObjCopy.keySet()) { final ParsedObject obj = idToObjCopy.get(id); final Map<String, Object> doc = convertObject(id, rule.getGlobalObjectType(), obj, data, timestamp, parentJsonValue, isPublic, lastVersion); final Map<String, Object> index = new HashMap<>(); index.put("_index", indexName); index.put("_type", getDataTableName()); index.put("parent", esParentId); if (esIds.containsKey(id)) { index.put("_id", esIds.get(id)); } final Map<String, Object> header = ImmutableMap.of("index", index); pw.println(UObject.transformObjectToString(header)); pw.println(UObject.transformObjectToString(doc)); } pw.close(); makeRequestBulk("POST", indexName, tempFile); updateLastVersionsInData(indexName, pguid, lastVersion); } finally { tempFile.delete(); } refreshIndex(indexName); } private Map<String, Object> convertObject( final GUID id, final SearchObjectType objectType, final ParsedObject obj, final SourceData data, final Instant timestamp, final String parentJson, final boolean isPublic, final int lastVersion) { Map<String, List<Object>> indexPart = new LinkedHashMap<>(); if (obj != null) { for (String key : obj.getKeywords().keySet()) { indexPart.put(getKeyProperty(key), obj.getKeywords().get(key)); } } Map<String, Object> doc = new LinkedHashMap<>(); doc.putAll(indexPart); doc.put(OBJ_GUID, id.toString()); doc.put(SEARCH_OBJ_TYPE, objectType.getType()); doc.put(SEARCH_OBJ_TYPE_VER, objectType.getVersion()); doc.put(SOURCE_TAGS, data.getSourceTags()); doc.put(OBJ_NAME, data.getName()); doc.put(OBJ_CREATOR, data.getCreator()); doc.put(OBJ_COPIER, data.getCopier().orNull()); doc.put(OBJ_PROV_MODULE, data.getModule().orNull()); doc.put(OBJ_PROV_METHOD, data.getMethod().orNull()); doc.put(OBJ_PROV_MODULE_VERSION, data.getVersion().orNull()); doc.put(OBJ_PROV_COMMIT_HASH, data.getCommitHash().orNull()); doc.put(OBJ_MD5, data.getMD5().orNull()); doc.put(OBJ_TIMESTAMP, timestamp.toEpochMilli()); doc.put(OBJ_PREFIX, toGUIDPrefix(id)); doc.put(OBJ_STORAGE_CODE, id.getStorageCode()); doc.put(OBJ_ACCESS_GROUP_ID, id.getAccessGroupId()); doc.put(OBJ_VERSION, id.getVersion()); doc.put(OBJ_IS_LAST, lastVersion == id.getVersion()); doc.put(OBJ_PUBLIC, isPublic); doc.put(OBJ_SHARED, false); if (obj != null) { doc.put("ojson", obj.getJson()); doc.put("pjson", parentJson); } return doc; } @Override public void flushIndexing(final ObjectTypeParsingRules rule) throws IOException { refreshIndex(checkIndex(rule, true)); } private Map<GUID, String> lookupDocIds(String indexName, Set<GUID> guids) throws IOException { // doc = {"query": {"bool": {"filter": [{"terms": {"guid": [guids]}}]}}} Map<String, Object> doc = ImmutableMap.of( "query", ImmutableMap.of( "bool", ImmutableMap.of( "filter", Arrays.asList(ImmutableMap.of( "terms", ImmutableMap.of( "guid", guids.stream().map(u -> u.toString()) .collect(Collectors.toList()))))))); String urlPath = "/" + indexName + "/" + getDataTableName() + "/_search"; Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); Map<GUID, String> ret = new LinkedHashMap<>(); @SuppressWarnings("unchecked") Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); @SuppressWarnings("unchecked") List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); for (Map<String, Object> hit : hitList) { String id = (String)hit.get("_id"); @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); GUID guid = new GUID((String) obj.get("guid")); ret.put(guid, id); } return ImmutableMap.copyOf(ret); } private Map<GUID, String> lookupParentDocIds(String indexName, Set<GUID> guids) throws IOException { // doc = {"query": {"bool": {"filter": [{"terms": {"pguid": [guids]}}]}}} Map<String, Object> doc = ImmutableMap.of("query", ImmutableMap.of("bool", ImmutableMap.of("filter", Arrays.asList(ImmutableMap.of("terms", ImmutableMap.of("pguid", guids.stream().map(u -> u.toString()).collect(Collectors.toList()))))))); String urlPath = "/" + indexName + "/" + getAccessTableName() + "/_search"; Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); Map<GUID, String> ret = new LinkedHashMap<>(); @SuppressWarnings("unchecked") Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); @SuppressWarnings("unchecked") List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); for (Map<String, Object> hit : hitList) { String id = (String)hit.get("_id"); @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); GUID guid = new GUID((String)obj.get("pguid")); ret.put(guid, id); } return ImmutableMap.copyOf(ret); } public Map<String, Set<GUID>> groupParentIdsByIndex(Set<GUID> ids) throws IOException { Set<String> parentIds = new LinkedHashSet<>(); for (GUID guid : ids) { parentIds.add(new GUID(guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), guid.getVersion(), null, null).toString()); } // doc = {"query": {"bool": {"filter": {"terms: ": {"pguid": [ids]}}}}, // "_source": ["pguid"]} Map<String, Object> doc = ImmutableMap.of("query", ImmutableMap.of("bool", ImmutableMap.of("filter", ImmutableMap.of("terms", ImmutableMap.of("pguid", parentIds)))), "_source", Arrays.asList("pguid")); String urlPath = "/" + indexNamePrefix + "*/" + getAccessTableName() + "/_search"; Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); Map<String, Set<GUID>> ret = new LinkedHashMap<>(); @SuppressWarnings("unchecked") Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); @SuppressWarnings("unchecked") List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); for (Map<String, Object> hit : hitList) { String indexName = (String)hit.get("_index"); Set<GUID> retSet = ret.get(indexName); if (retSet == null) { retSet = new LinkedHashSet<>(); ret.put(indexName, retSet); } @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); GUID guid = new GUID((String)obj.get("pguid")); retSet.add(guid); } return ImmutableMap.copyOf(ret); } private Map<String, Object> createFilter(String queryType, String keyName, Object value) { Map<String, Object> term = new LinkedHashMap<>(); // term = {keyname: value}? if (keyName != null) { term.put(keyName, value); } Map<String, Object> termWrapper = new LinkedHashMap<>(); termWrapper.put(queryType, ImmutableMap.copyOf(term)); // return = {queryType: {keyname: value}?} return ImmutableMap.copyOf(termWrapper); } private Map<String, Object> createRangeFilter(String keyName, Object gte, Object lte) { Map<String, Object> range = new LinkedHashMap<>(); if (gte != null) { range.put("gte", gte); } if (lte != null) { range.put("lte", lte); } Map<String, Object> termWrapper = ImmutableMap.of("range", ImmutableMap.of(keyName, ImmutableMap.copyOf(range))); return termWrapper; } // throws IOexceptions for elastic connection issues & deserializaion issues @Override public Map<GUID, Boolean> checkParentGuidsExist(final Set<GUID> guids) throws IOException { Set<GUID> parentGUIDs = guids.stream().map(guid -> new GUID( guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), guid.getVersion(), null, null)) .collect(Collectors.toSet()); final String indexName = getAnyIndexPattern(); // In next operation map value may contain one of possible parents in case objectType==null final Map<GUID, String> map = lookupParentDocIds(indexName, parentGUIDs); return ImmutableMap.copyOf(parentGUIDs.stream().collect( Collectors.toMap(Function.identity(), guid -> map.containsKey(guid)))); } private Integer loadLastVersion(String reqIndexName, GUID parentGUID, Integer processedVersion) throws IOException { if (reqIndexName == null) { reqIndexName = getAnyIndexPattern(); } String prefix = toGUIDPrefix(parentGUID); // doc = {"query": {"bool": {"filter": [{"term": {"prefix": prefix}}]}}} Map<String, Object> doc = ImmutableMap.of("query", ImmutableMap.of("bool", ImmutableMap.of("filter", Arrays.asList(ImmutableMap.of( "term", ImmutableMap.of("prefix", prefix)))))); String urlPath = "/" + reqIndexName + "/" + getAccessTableName() + "/_search"; Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); @SuppressWarnings("unchecked") Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); Integer ret = null; @SuppressWarnings("unchecked") List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); for (Map<String, Object> hit : hitList) { @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); int version = (Integer)obj.get("version"); if (ret == null || ret < version) { ret = version; } } if (processedVersion != null && (ret == null || ret < processedVersion)) { ret = processedVersion; } return ret; } private int updateLastVersionsInData(String indexName, GUID parentGUID, int lastVersion) throws IOException, IndexingConflictException { if (indexName == null) { indexName = getAnyIndexPattern(); } // query = {"bool": {"filter": [{"term": {"prefix": prefix}}]}} Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("filter", Arrays.asList(ImmutableMap.of("term", ImmutableMap.of("prefix", toGUIDPrefix(parentGUID)))))); // params = {"lastver": lastVersion} final Map<String, Object> params = ImmutableMap.of("lastver", lastVersion); // script = {"inline": "ctx._source.islast = (ctx._source.version == params.lastver)", // "params": {"lastver": lastVersion}} Map<String, Object> script = ImmutableMap.of( "inline", "ctx._source.islast = (ctx._source.version == params.lastver);", "params", params); // doc = {"query": {"bool": {"filter": [{"term": {"prefix": prefix}}]}}, // "script": {"inline": "ctx._source.islast = (ctx._source.version == params.lastver)", // "params": {"lastver": lastVersion}}} Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getDataTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated"); } private Map<GUID, String> checkParentDoc(String indexName, Set<GUID> parentGUIDs, boolean isPublic, int lastVersion) throws IOException, IndexingConflictException { boolean changed = false; Map<GUID, String> ret = new LinkedHashMap<>(lookupParentDocIds(indexName, parentGUIDs)); for (GUID parentGUID : parentGUIDs) { if (ret.containsKey(parentGUID)) { continue; } String prefix = toGUIDPrefix(parentGUID); Map<String, Object> doc = new LinkedHashMap<>(); doc.put("pguid", parentGUID.toString()); doc.put("prefix", prefix); doc.put("version", parentGUID.getVersion()); Set<Integer> accessGroupIds = new LinkedHashSet<>(Arrays.asList( ADMIN_ACCESS_GROUP)); if (parentGUID.getAccessGroupId() != null) { accessGroupIds.add(parentGUID.getAccessGroupId()); } if (isPublic) { accessGroupIds.add(PUBLIC_ACCESS_GROUP); } Set<Integer> lastinGroupIds = parentGUID.getVersion() == lastVersion ? accessGroupIds : Collections.emptySet(); doc.put("lastin", lastinGroupIds); doc.put("groups", accessGroupIds); doc.put("extpub", new ArrayList<Integer>()); Response resp = makeRequest("POST", "/" + indexName + "/" + getAccessTableName() + "/", doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); ret.put(parentGUID, (String)data.get("_id")); changed = true; updateAccessGroupForVersions(indexName, parentGUID, lastVersion, parentGUID.getAccessGroupId(), isPublic, true); } if (changed) { refreshIndex(indexName); } return ImmutableMap.copyOf(ret); } private static final String UPDATE_ACC_GRP_VERS_TEMPLATE = "if (ctx._source.lastin.indexOf(params.%1$s) >= 0) {\n" + " if (ctx._source.version != params.lastver) {\n" + " ctx._source.lastin.remove(ctx._source.lastin.indexOf(params.%1$s));\n" + " if (ctx._source.extpub.indexOf(params.%1$s) >= 0) {\n" + " ctx._source.extpub.remove(ctx._source.extpub.indexOf(params.%1$s));\n" + " }\n" + " }\n" + "} else {\n" + " if (ctx._source.version == params.lastver) {\n" + " ctx._source.lastin.add(params.%1$s);\n" + " if (ctx._source.groups.indexOf(params.%1$s) < 0) {\n" + " ctx._source.groups.add(params.%1$s);\n" + " }\n" + " }\n" + "}\n"; //IO exception thrown for deserialization & elasticsearch contact errors /* calling this method with accessGroupId == null and both booleans false is an error. */ private boolean updateAccessGroupForVersions( String indexName, final GUID guid, final int lastVersion, final Integer accessGroupId, final boolean includePublicAccessID, final boolean includeAdminAccessID) throws IOException, IndexingConflictException { /* this method will cause at most 6 script compilations, which seems like a lot... * Could make the script always the same and put in ifs but this should be ok for now. */ if (indexName == null) { indexName = getAnyIndexPattern(); } // query = {"bool": {"must": [{"term": {"prefix": prefix}?}]}} Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("must", Arrays.asList( createFilter("term", "prefix", toGUIDPrefix(guid))))); // params = {"lastver": lastVersion, // ("accgrp": accessGroupId)?, // ("pubaccgrp": -1)?, // ("pubaccgrp": -2)?} StringBuilder inline = new StringBuilder(); final Map<String, Object> params = new HashMap<>(); params.put("lastver", lastVersion); if (accessGroupId != null) { inline.append(String.format(UPDATE_ACC_GRP_VERS_TEMPLATE, "accgrp")); params.put("accgrp", accessGroupId); } if (includePublicAccessID) { inline.append(String.format(UPDATE_ACC_GRP_VERS_TEMPLATE, "pubaccgrp")); params.put("pubaccgrp", PUBLIC_ACCESS_GROUP); } if (includeAdminAccessID) { inline.append(String.format(UPDATE_ACC_GRP_VERS_TEMPLATE, "adminaccgrp")); params.put("adminaccgrp", ADMIN_ACCESS_GROUP); } Map<String, Object> script = new LinkedHashMap<>(); script.put("inline", inline.toString()); script.put("params", ImmutableMap.copyOf(params)); Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getAccessTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated") > 0; } private boolean removeAccessGroupForVersion(String indexName, GUID guid, int accessGroupId) throws IOException, IndexingConflictException { if (indexName == null) { indexName = getAnyIndexPattern(); } // This flag shows that we work with other than physical access group this object exists in. boolean fromAllGroups = accessGroupId != guid.getAccessGroupId(); String pguid = new GUID(guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), guid.getVersion(), null, null).toString(); Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("must", Arrays.asList( createFilter("term", "pguid", pguid), createFilter("term", "lastin", accessGroupId)))); final Map<String, Object> params = ImmutableMap.of("accgrp", accessGroupId); Map<String, Object> script = ImmutableMap.of( "inline", "ctx._source.lastin.remove(ctx._source.lastin.indexOf(params.accgrp));\n" + "if (ctx._source.extpub.indexOf(params.accgrp) >= 0) {\n" + " ctx._source.extpub.remove(ctx._source.extpub.indexOf(params.accgrp));\n" + "}\n" + (fromAllGroups ? ( "int pos = ctx._source.groups.indexOf(params.accgrp);\n" + "if (pos >= 0) {\n" + " ctx._source.groups.remove(pos);\n" + "}\n") : ""), "params", params); Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getAccessTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated") > 0; } private boolean updateBooleanFieldInData(String indexName, GUID parentGUID, String field, boolean value) throws IOException, IndexingConflictException { if (indexName == null) { indexName = getAnyIndexPattern(); } Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("must", Arrays.asList(createFilter("term", "prefix", toGUIDPrefix(parentGUID)), createFilter("term", "version", parentGUID.getVersion())))); final Map<String, Object> params = ImmutableMap.of("field", field, "value", value); Map<String, Object> script = ImmutableMap.of("inline", "ctx._source[params.field] = params.value;", "params", params); Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getDataTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated") > 0; } private String toGUIDPrefix(GUID parentGUID) { return new GUID(parentGUID.getStorageCode(), parentGUID.getAccessGroupId(), parentGUID.getAccessGroupObjectId(), null, null, null).toString(); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public int setNameOnAllObjectVersions(final GUID object, final String newName) throws IOException, IndexingConflictException { return setFieldOnObject(object, OBJ_NAME, newName, true); } /* expects that GUID does not have sub object info */ // TODO CODE allow providing index name for optimization private int setFieldOnObject( final GUID object, final String field, final Object value, final boolean allVersions) throws IOException, IndexingConflictException { final String index = getAnyIndexPattern(); final Map<String, Object> query; if (allVersions) { query = createFilter("term", "prefix", toGUIDPrefix(object)); } else { query = createFilter("term", "guid", object.toString()); } final Map<String, Object> script = ImmutableMap.of( "inline", "ctx._source[params.field] = params.value", "params", ImmutableMap.of("field", field, "value", value)); final Map<String, Object> doc = ImmutableMap.of( "query", query, "script", script); final String urlPath = "/" + index + "/" + getDataTableName() + "/_update_by_query"; final Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") final Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (int) data.get("updated"); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void shareObjects(Set<GUID> guids, int accessGroupId, boolean isExternalPublicGroup) throws IOException, IndexingConflictException { Map<String, Set<GUID>> indexToGuids = groupParentIdsByIndex(guids); for (String indexName : indexToGuids.keySet()) { Set<GUID> toAddExtPub = new LinkedHashSet<GUID>(); boolean needRefresh = false; for (GUID guid : indexToGuids.get(indexName)) { if (updateAccessGroupForVersions(indexName, guid, guid.getVersion(), accessGroupId, false, false)) { needRefresh = true; } if (accessGroupId == PUBLIC_ACCESS_GROUP) { if (updateBooleanFieldInData(indexName, guid, "public", true)) { needRefresh = true; } } else if (accessGroupId != guid.getAccessGroupId()) { if (updateBooleanFieldInData(indexName, guid, "shared", true)) { needRefresh = true; } if (isExternalPublicGroup) { toAddExtPub.add(guid); } } } if (needRefresh) { refreshIndex(indexName); } if (!toAddExtPub.isEmpty()) { needRefresh = false; for (GUID guid : indexToGuids.get(indexName)) { if (addExtPubForVersion(indexName, guid, accessGroupId)) { needRefresh = true; } } if (needRefresh) { refreshIndex(indexName); } } } } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void unshareObjects(Set<GUID> guids, int accessGroupId) throws IOException, IndexingConflictException { Map<String, Set<GUID>> indexToGuids = groupParentIdsByIndex(guids); for (String indexName : indexToGuids.keySet()) { boolean needRefresh = false; for (GUID guid : indexToGuids.get(indexName)) { if (removeAccessGroupForVersion(indexName, guid, accessGroupId)) { needRefresh = true; } if (accessGroupId == PUBLIC_ACCESS_GROUP) { if (updateBooleanFieldInData(indexName, guid, "public", false)) { needRefresh = true; } } //TODO NOW how is share bit unset? } if (needRefresh) { refreshIndex(indexName); } } } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void deleteAllVersions(final GUID guid) throws IOException, IndexingConflictException { // could optimize later by making LLV return the index name final Integer ver = loadLastVersion(null, guid, null); if (ver == null) { //TODO NOW throw exception? means a delete event occurred when there were no objects return; } final String indexName = getAnyIndexPattern(); setFieldOnObject(withVersion(guid, ver), "islast", false, false); // -3 is a hack to always remove access groups updateAccessGroupForVersions(indexName, guid, -3, guid.getAccessGroupId(), false, false); /* changing the public field doesn't make a ton of sense - the object is still in a public * workspace. * TODO NOW add a deleted flag, use that instead. */ // setFieldOnObjectForAllVersions(guid, "public", false); //TODO NOW this doesn't handle removing public (-1) from the access doc because it can't know that's the right thing to do //TODO NOW admin access group id has same problem as public access group id } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void undeleteAllVersions(final GUID guid) throws IOException, IndexingConflictException { // could optimize later by making LLV return the index name final Integer ver = loadLastVersion(null, guid, null); if (ver == null) { //TODO NOW throw exception? means an undelete event occurred when there were no objects return; } updateLastVersionsInData(null, guid, ver); updateAccessGroupForVersions(null, guid, ver, guid.getAccessGroupId(), false, true); // TODO NOW remove deleted flag from delete all versions } private GUID withVersion(final GUID guid, int ver) { return new GUID(guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), ver, null, null); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void publishObjects(Set<GUID> guids) throws IOException, IndexingConflictException { shareObjects(guids, PUBLIC_ACCESS_GROUP, false); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void unpublishObjects(Set<GUID> guids) throws IOException, IndexingConflictException { unshareObjects(guids, PUBLIC_ACCESS_GROUP); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void publishAllVersions(final GUID guid) throws IOException, IndexingConflictException { setFieldOnObject(guid, "public", true, true); } //IO exception thrown for deserialization & elasticsearch contact errors @Override public void unpublishAllVersions(final GUID guid) throws IOException, IndexingConflictException { setFieldOnObject(guid, "public", false, true); } private boolean addExtPubForVersion(String indexName, GUID guid, int accessGroupId) throws IOException, IndexingConflictException { // Check that we work with other than physical access group this object exists in. if (accessGroupId == guid.getAccessGroupId()) { throw new IllegalStateException("Access group should be external"); } if (indexName == null) { indexName = getAnyIndexPattern(); } String pguid = new GUID(guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), guid.getVersion(), null, null).toString(); Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("must", Arrays.asList(createFilter("term", "pguid", pguid)))); final Map<String, Object> params = ImmutableMap.of("accgrp", accessGroupId); Map<String, Object> script = ImmutableMap.of( "inline", "if (ctx._source.extpub.indexOf(params.accgrp) < 0) {\n" + " ctx._source.extpub.add(params.accgrp);\n" + "}\n", "params", params); Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getAccessTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated") > 0; } @Override public void publishObjectsExternally(Set<GUID> guids, int accessGroupId) throws IOException, IndexingConflictException { Map<String, Set<GUID>> indexToGuids = groupParentIdsByIndex(guids); for (String indexName : indexToGuids.keySet()) { boolean needRefresh = false; for (GUID guid : indexToGuids.get(indexName)) { if (addExtPubForVersion(indexName, guid, accessGroupId)) { needRefresh = true; } } if (needRefresh) { refreshIndex(indexName); } } } private boolean removeExtPubForVersion(String indexName, GUID guid, int accessGroupId) throws IOException, IndexingConflictException { // Check that we work with other than physical access group this object exists in. if (accessGroupId == guid.getAccessGroupId()) { throw new IllegalStateException("Access group should be external"); } if (indexName == null) { indexName = getAnyIndexPattern(); } String pguid = new GUID(guid.getStorageCode(), guid.getAccessGroupId(), guid.getAccessGroupObjectId(), guid.getVersion(), null, null).toString(); Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("must", Arrays.asList(createFilter("term", "pguid", pguid), createFilter("term", "extpub", accessGroupId)))); final Map<String, Object> params = ImmutableMap.of("accgrp", accessGroupId); Map<String, Object> script = ImmutableMap.of( "inline", "ctx._source.extpub.remove(ctx._source.extpub.indexOf(params.accgrp));\n", "params", params); Map<String, Object> doc = ImmutableMap.of("query", query, "script", script); String urlPath = "/" + indexName + "/" + getAccessTableName() + "/_update_by_query"; Response resp = makeRequest("POST", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); return (Integer)data.get("updated") > 0; } @Override public void unpublishObjectsExternally(Set<GUID> guids, int accessGroupId) throws IOException, IndexingConflictException { Map<String, Set<GUID>> indexToGuids = groupParentIdsByIndex(guids); for (String indexName : indexToGuids.keySet()) { boolean needRefresh = false; for (GUID guid : indexToGuids.get(indexName)) { if (removeExtPubForVersion(indexName, guid, accessGroupId)) { needRefresh = true; } } if (needRefresh) { refreshIndex(indexName); } } } @Override public List<ObjectData> getObjectsByIds(Set<GUID> ids) throws IOException { PostProcessing pp = new PostProcessing(); pp.objectInfo = true; pp.objectData = true; pp.objectKeys = true; return getObjectsByIds(ids, pp); } private Map<String, Object> createHighlightQuery(){ return ImmutableMap.of("fields", ImmutableMap.of("*", ImmutableMap.of("require_field_match", false))); } @Override public List<ObjectData> getObjectsByIds(final Set<GUID> ids, final PostProcessing pp) throws IOException { final Map<String, Object> query = ImmutableMap.of("bool", ImmutableMap.of("filter", ImmutableMap.of("terms", ImmutableMap.of("guid", ids.stream().map(u -> u.toString()).collect(Collectors.toList()))))); final Map<String, Object> doc = new LinkedHashMap<>(); doc.put("query", query); if (Objects.nonNull(pp) && pp.objectHighlight) { doc.put("highlight", createHighlightQuery()); } final String urlPath = "/" + indexNamePrefix + "*/" + getDataTableName() + "/_search"; final Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") final Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); final List<ObjectData> ret = new ArrayList<>(); @SuppressWarnings("unchecked") final Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); @SuppressWarnings("unchecked") final List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); for (Map<String, Object> hit : hitList) { @SuppressWarnings("unchecked") final Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); @SuppressWarnings("unchecked") final Map<String, List<String>> highlightRes = (Map<String, List<String>>) hit.get("highlight"); final ObjectData item = buildObjectData(obj, highlightRes, pp); ret.add(item); } return ret; } private ObjectData buildObjectData( final Map<String, Object> obj, final Map<String, List<String>> highlight, final PostProcessing pp) { // TODO: support sub-data selection based on objectDataIncludes (acts on parent json or sub object json) GUID guid = new GUID((String) obj.get("guid")); final ObjectData.Builder b = ObjectData.getBuilder(guid); if (pp.objectInfo) { b.withNullableObjectName((String) obj.get(OBJ_NAME)); b.withNullableCreator((String) obj.get(OBJ_CREATOR)); b.withNullableCopier((String) obj.get(OBJ_COPIER)); b.withNullableModule((String) obj.get(OBJ_PROV_MODULE)); b.withNullableMethod((String) obj.get(OBJ_PROV_METHOD)); b.withNullableModuleVersion((String) obj.get(OBJ_PROV_MODULE_VERSION)); b.withNullableCommitHash((String) obj.get(OBJ_PROV_COMMIT_HASH)); b.withNullableMD5((String) obj.get(OBJ_MD5)); b.withNullableType(new SearchObjectType( (String) obj.get(SEARCH_OBJ_TYPE), (Integer) obj.get(SEARCH_OBJ_TYPE_VER))); // sometimes this is a long, sometimes it's an int b.withNullableTimestamp(Instant.ofEpochMilli( ((Number) obj.get(OBJ_TIMESTAMP)).longValue())); @SuppressWarnings("unchecked") final List<String> sourceTags = (List<String>) obj.get(SOURCE_TAGS); if (sourceTags != null) { for (final String tag: sourceTags) { b.withSourceTag(tag); } } } if (pp.objectData) { final String ojson = (String) obj.get("ojson"); if (ojson != null) { b.withNullableData(UObject.transformStringToObject( ojson, Object.class)); } final String pjson = (String) obj.get("pjson"); if (pjson != null) { b.withNullableParentData(UObject.transformStringToObject(pjson, Object.class)); } } if (pp.objectKeys) { for (final String key : obj.keySet()) { if (key.startsWith("key.")) { final Object objValue = obj.get(key); String textValue; if (objValue instanceof List) { @SuppressWarnings("unchecked") final List<Object> objValue2 = (List<Object>) objValue; textValue = objValue2.stream().map(Object::toString) .collect(Collectors.joining(", ")); } else { textValue = String.valueOf(objValue); } b.withKeyProperty(stripKeyPrefix(key), textValue); } } } //because elastic sometimes returns highlight as null instead of empty map. if (pp.objectHighlight && highlight != null) { for(final String key : highlight.keySet()) { b.withHighlight(getReadableKeyNames(key, guid), highlight.get(key)); } } return b.build(); } private String getReadableKeyNames(final String key, final GUID guid) throws IllegalStateException{ if (key.startsWith("key.")) { return stripKeyPrefix(key); } else if(READABLE_NAMES.containsKey(key)) { return READABLE_NAMES.get(key); } else { //this should not happen. Untested String message = "Object with guid " + guid.toString() + " has unexpected key: " + key; throw new IllegalStateException(message); } } private String stripKeyPrefix(final String key){ return key.substring(4); } private Map<String, Object> createPublicShouldBlock(boolean withAllHistory) { List<Object> must0List = new ArrayList<>(); must0List.add(createFilter("term", "public", true)); if (!withAllHistory) { must0List.add(createFilter("term", "islast", true)); } Map<String, Object> bool0Wrapper = ImmutableMap.of("bool", ImmutableMap.of("must", must0List)); return bool0Wrapper; } private Map<String, Object> createOwnerShouldBlock(AccessFilter accessFilter) { List<Object> must1List = new ArrayList<>(); if (!accessFilter.isAdmin) { Set<Integer> accGroups = accessFilter.accessGroupIds; if (accGroups == null) { accGroups = Collections.emptySet(); } must1List.add(createFilter("terms", "accgrp", accGroups)); } if (!accessFilter.withAllHistory) { must1List.add(createFilter("term", "islast", true)); } Map<String, Object> bool1Wrapper = ImmutableMap.of("bool", ImmutableMap.of("must", must1List)); return bool1Wrapper; } private Map<String, Object> createSharedShouldBlock(Map<String, Object> mustForShared) { List<Object> must2List = new ArrayList<>(Arrays.asList( createFilter("term", "shared", true), mustForShared)); Map<String, Object> bool2Wrapper = ImmutableMap.of("bool", ImmutableMap.of("must", must2List)); return bool2Wrapper; } //TODO VERS should this return SearchObjectType -> Integer map? Maybe an option to combine versions @Override public Map<String, Integer> searchTypes( final MatchFilter matchFilter, final AccessFilter accessFilter) throws IOException { Map<String, Object> mustForShared = createAccessMustBlock(accessFilter); if (mustForShared == null) { return Collections.emptyMap(); } //TODO VERS if this aggregates by type version, need to add the version field to the terms Map<String, Object> aggs = ImmutableMap.of("types", ImmutableMap.of("terms", ImmutableMap.of("field", SEARCH_OBJ_TYPE))); Map<String, Object> doc = ImmutableMap.of( "query", createObjectQuery(matchFilter, accessFilter), "aggregations", aggs, "size", 0); String urlPath = "/" + indexNamePrefix + "*" + (matchFilter.isExcludeSubObjects() ? EXCLUDE_SUB_OJBS_URL_SUFFIX : "") + "/" + getDataTableName() + "/_search"; Response resp = makeRequestNoConflict("GET", urlPath, doc); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); @SuppressWarnings("unchecked") Map<String, Object> aggMap = (Map<String, Object>) data.get("aggregations"); @SuppressWarnings("unchecked") Map<String, Object> typeMap = (Map<String, Object>) aggMap.get("types"); @SuppressWarnings("unchecked") List<Map<String, Object>> buckets = (List<Map<String, Object>>) typeMap.get("buckets"); Map<String, Integer> ret = new TreeMap<>(); for (Map<String, Object> bucket : buckets) { String objType = (String)bucket.get("key"); Integer count = (Integer)bucket.get("doc_count"); ret.put(objType, count); } return ImmutableMap.copyOf(ret); } private Map<String, Object> createObjectQuery( final MatchFilter matchFilter, final AccessFilter accessFilter) { final List<Object> shouldList = new ArrayList<>(); // Public block (we exclude it for admin because it's covered by owner block) if (accessFilter.withPublic && !accessFilter.isAdmin) { shouldList.add(createPublicShouldBlock(accessFilter.withAllHistory)); } // Owner block shouldList.add(createOwnerShouldBlock(accessFilter)); // Shared block shouldList.add(createSharedShouldBlock(createAccessMustBlock(accessFilter))); // Rest of query final Map<String, Object> bool = new HashMap<>(); bool.putAll(prepareMatchFilters(matchFilter)); bool.put("filter", Arrays.asList(ImmutableMap.of("bool", ImmutableMap.of( "should", shouldList)))); return ImmutableMap.of("bool", bool); } @Override public FoundHits searchIds( final List<String> objectTypes, final MatchFilter matchFilter, final List<SortingRule> sorting, final AccessFilter accessFilter, final Pagination pagination) throws IOException { return queryHits(objectTypes, matchFilter, sorting, accessFilter, pagination, null); } @Override public FoundHits searchObjects( final List<String> objectTypes, final MatchFilter matchFilter, final List<SortingRule> sorting, final AccessFilter accessFilter, final Pagination pagination, final PostProcessing postProcessing) throws IOException { return queryHits(objectTypes, matchFilter, sorting, accessFilter, pagination, postProcessing); } // this is only used for tests public Set<GUID> searchIds( final List<String> objectTypes, final MatchFilter matchFilter, final List<SortingRule> sorting, final AccessFilter accessFilter) throws IOException { return searchIds(objectTypes, matchFilter, sorting, accessFilter, null).guids; } private Map<String, Object> prepareMatchFilters(MatchFilter matchFilter) { final List<Map<String, Object>> matches = new ArrayList<>(); if (matchFilter.getFullTextInAll().isPresent()) { final LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put("query", matchFilter.getFullTextInAll().get()); query.put("operator", "and"); final LinkedHashMap<String, Object> allQuery = new LinkedHashMap<>(); allQuery.put("_all", query); final LinkedHashMap<String, Object> match = new LinkedHashMap<>(); match.put("match",allQuery); matches.add(match); } // TODO: support for matchFilter.accessGroupId (e.g. reduce search scope to one group) /*if (matchFilter.accessGroupId != null) { ret.add(createAccessMustBlock(new LinkedHashSet<>(Arrays.asList( matchFilter.accessGroupId)), withAllHistory)); }*/ if (matchFilter.getObjectName().isPresent()) { // this seems like a bug...? matches.add(createFilter("match", OBJ_NAME, matchFilter.getFullTextInAll().get())); } for (final String keyName : matchFilter.getLookupInKeys().keySet()) { final MatchValue value = matchFilter.getLookupInKeys().get(keyName); final String keyProp = getKeyProperty(keyName); if (value.value != null) { matches.add(createFilter("term", keyProp, value.value)); } else if (value.minInt != null || value.maxInt != null) { matches.add(createRangeFilter(keyProp, value.minInt, value.maxInt)); } else if (value.minDate != null || value.maxDate != null) { matches.add(createRangeFilter(keyProp, value.minDate, value.maxDate)); } else if (value.minDouble != null || value.maxDouble != null) { matches.add(createRangeFilter(keyProp, value.minDouble, value.maxDouble)); } } if (matchFilter.getTimestamp().isPresent()) { matches.add(createRangeFilter(OBJ_TIMESTAMP, matchFilter.getTimestamp().get().minDate, matchFilter.getTimestamp().get().maxDate)); } final Map<String, Object> ret = new HashMap<>(); if (!matchFilter.getSourceTags().isEmpty()) { final Map<String, Object> tagsQuery = ImmutableMap.of("terms", ImmutableMap.of( SOURCE_TAGS, matchFilter.getSourceTags())); if (matchFilter.isSourceTagsBlacklist()) { ret.put("must_not", tagsQuery); } else { matches.add(tagsQuery); } } // TODO: support parent guid (reduce search scope to one object, e.g. features of one geneom) if (ret.isEmpty() && matches.isEmpty()) { matches.add(createFilter("match_all", null, null)); } if (!matches.isEmpty()) { ret.put("must", matches); } return ret; } private Map<String, Object> createAccessMustBlock(AccessFilter accessFilter) { Set<Integer> accessGroupIds = new LinkedHashSet<>(); if (accessFilter.isAdmin) { accessGroupIds.add(ADMIN_ACCESS_GROUP); } else { if (accessFilter.accessGroupIds != null) { accessGroupIds.addAll(accessFilter.accessGroupIds); } if (accessFilter.withPublic) { accessGroupIds.add(PUBLIC_ACCESS_GROUP); } } if (accessGroupIds.isEmpty()) { return null; } return createAccessMustBlock(accessGroupIds, accessFilter.withAllHistory, accessFilter.withPublic); } private Map<String, Object> createAccessMustBlock(Set<Integer> accessGroupIds, boolean withAllHistory, boolean withPublic) { // should = [] List<Object> should = new ArrayList<>(); // match = {groupListProp: [accessGroupIds]} String groupListProp = withAllHistory ? "groups" : "lastin"; // I think lastin means last version even though version is orthogonal to the concept of groups? // terms = {"terms": { groupListProp: [accessGroupIds]}} Map<String, Object> terms = ImmutableMap.of("terms", ImmutableMap.of(groupListProp, accessGroupIds)); // should = [{"terms": {groupListProp: [accessGroupIds]}}] should.add(terms); if (withPublic) { // Case of public workspaces containing DataPalette referencing to given object // We basically check how many public workspaces (external comparing to home // workspace of given object) have DataPalettes referencing given object (and // version). If this number is 0 then object+version is not visible as public // through DataPalettes. If it's >0 (which is the same as existence of keywords // in 'extpub') then it's visible. // exists = {"field", "extpub"} // existsWrapper = {"exists": {"field", "extpub"}} Map<String, Object> existwrapper = ImmutableMap.of("exists", ImmutableMap.of("field", "extpub")); // should = [{"terms": {groupListProp: [accessGroupIds]}} // {"exists": {"field", "extpub"}}] should.add(existwrapper); } // hasParentWrapper = {"hasParent": {"parent_type": "access", // "query": {"bool": {"should": [{"terms": {groupListProp: [accessGroupIds]}} // {"exists": {"field", "extpub"}}?]}}}} Map<String, Object> hasParentWrapper = ImmutableMap.of("has_parent", ImmutableMap.of("parent_type", getAccessTableName(), "query", ImmutableMap.of("bool", ImmutableMap.of("should", should)))); return hasParentWrapper; } private FoundHits queryHits( final List<String> objectTypes, final MatchFilter matchFilter, List<SortingRule> sorting, final AccessFilter accessFilter, final Pagination pg, final PostProcessing pp) throws IOException { // initialize args int pgStart = pg == null || pg.start == null ? 0 : pg.start; int pgCount = pg == null || pg.count == null ? 50 : pg.count; Pagination pagination = new Pagination(pgStart, pgCount); if (sorting == null || sorting.isEmpty()) { final SortingRule sr = SortingRule.getStandardPropertyBuilder(R_OBJ_TIMESTAMP).build(); sorting = Arrays.asList(sr); } FoundHits ret = new FoundHits(); ret.pagination = pagination; ret.sortingRules = sorting; final Map<String, Object> mustForShared = createAccessMustBlock(accessFilter); if (mustForShared == null) { ret.total = 0; ret.guids = Collections.emptySet(); return ret; } Map<String, Object> doc = new LinkedHashMap<>(); doc.put("query", createObjectQuery(matchFilter, accessFilter)); if (Objects.nonNull(pp) && pp.objectHighlight) { doc.put("highlight", createHighlightQuery()); } doc.put("from", pagination.start); doc.put("size", pagination.count); boolean loadObjects = pp != null && (pp.objectInfo || pp.objectData || pp.objectKeys || pp.objectHighlight); if (!loadObjects) { doc.put("_source", Arrays.asList("guid")); } doc.put("sort", createSortQuery(sorting)); validateObjectTypes(objectTypes); String indexName; // search unconstrained by object type if (objectTypes.isEmpty()) { indexName = getAnyIndexPattern(); } // search constrained by object types else { final List<String> rr = new LinkedList<>(); for (final String type: objectTypes) { rr.add(checkIndex(type)); } indexName = String.join(",", rr); } if (matchFilter.isExcludeSubObjects()) { indexName += EXCLUDE_SUB_OJBS_URL_SUFFIX; } final String urlPath = "/" + indexName + "/" + getDataTableName() + "/_search"; final Response resp = makeRequestNoConflict("GET", urlPath, ImmutableMap.copyOf(doc)); @SuppressWarnings("unchecked") final Map<String, Object> data = UObject.getMapper().readValue( resp.getEntity().getContent(), Map.class); ret.guids = new LinkedHashSet<>(); @SuppressWarnings("unchecked") final Map<String, Object> hitMap = (Map<String, Object>) data.get("hits"); ret.total = (Integer)hitMap.get("total"); @SuppressWarnings("unchecked") final List<Map<String, Object>> hitList = (List<Map<String, Object>>) hitMap.get("hits"); if (loadObjects) { ret.objects = new ArrayList<>(); } for (Map<String, Object> hit : hitList) { @SuppressWarnings("unchecked") final Map<String, Object> obj = (Map<String, Object>) hit.get("_source"); @SuppressWarnings("unchecked") final Map<String, List<String>> highlightRes = (Map<String, List<String>>) hit.get("highlight"); final String guidText = (String)obj.get("guid"); ret.guids.add(new GUID(guidText)); if (loadObjects) { ret.objects.add(buildObjectData(obj, highlightRes, pp)); } } return ret; } private List<Object> createSortQuery(final List<SortingRule> sorting) { final List<Object> sort = new ArrayList<>(); for (final SortingRule sr : sorting) { final Map<String, String> order = ImmutableMap.of ("order", sr.isAscending() ? "asc" : "desc"); final Map<String, Object> sortWrapper; if (sr.isKeyProperty()) { sortWrapper = ImmutableMap.of(getKeyProperty(sr.getKeyProperty().get()), order); } else { if (!READABLE_NAMES.inverse().containsKey(sr.getStandardProperty().get())) { throw new IllegalArgumentException("Unknown object property " + sr.getStandardProperty().get()); } sortWrapper = ImmutableMap.of( READABLE_NAMES.inverse().get(sr.getStandardProperty().get()), order); } sort.add(sortWrapper); } return sort; } private String getKeyProperty(final String keyName) { return "key." + keyName; } public Set<String> listIndeces() throws IOException { Set<String> ret = new TreeSet<>(); @SuppressWarnings("unchecked") Map<String, Object> data = UObject.getMapper().readValue( makeRequestNoConflict("GET", "/_aliases", null).getEntity().getContent(), Map.class); ret.addAll(data.keySet()); return ret; } public Response deleteIndex(String indexName) throws IOException { return makeRequestNoConflict("DELETE", "/" + indexName, null); } public Response refreshIndex(String indexName) throws IOException { return makeRequestNoConflict("POST", "/" + indexName + "/_refresh", null); } /** Refresh the elasticsearch index, where the index prefix is set by * {@link #setIndexNamePrefix(String)}. Primarily used for testing. * @param rule the parsing rules that describes the index. * @return the response from the ElasticSearch server. * @throws IOException if an IO error occurs. */ public Response refreshIndexByType(final ObjectTypeParsingRules rule) throws IOException { return refreshIndex(toIndexString(rule)); } private RestClient getRestClient() { if (restClient == null) { RestClientBuilder restClientBld = RestClient.builder(esHost); restClientBld.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder.setConnectTimeout(10000) .setSocketTimeout(10 * 60 * 1000); } }).setMaxRetryTimeoutMillis(10 * 60 * 1000); List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); //headers.add(new BasicHeader("Role", "Read")); restClientBld.setDefaultHeaders(headers.toArray(new Header[headers.size()])); if (esUser != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUser, esPassword)); restClientBld.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder hacb) { return hacb.setDefaultCredentialsProvider(credentialsProvider); } }); } restClient = restClientBld.build(); } return restClient; } public Response makeRequestNoConflict( final String reqType, final String urlPath, final Map<String, ?> doc) throws IOException { try { return makeRequest(reqType, urlPath, doc); } catch (IndexingConflictException e) { // this is impossible to test, and so is not tested throw new IOException( "This operation is not expected to result in a conflict, yet it occurred: " + e.getMessage(), e); } } public Response makeRequest( final String reqType, final String urlPath, final Map<String, ?> doc) throws IOException, IndexingConflictException { return makeRequest(reqType, urlPath, doc, Collections.emptyMap()); } public Response makeRequestBulk( final String reqType, final String indexName, final File jsonData) throws IOException, IndexingConflictException { try (InputStream is = new FileInputStream(jsonData)) { return makeRequest(reqType, "/" + indexName + "/_bulk", Collections.emptyMap(), new InputStreamEntity(is)); } } private Response makeRequest( final String reqType, final String urlPath, final Map<String, ?> doc, final Map<String, String> attributes) throws IOException, IndexingConflictException { return makeRequest(reqType, urlPath, attributes, doc == null ? null : stringEntity( UObject.transformObjectToString(doc))); } private Response makeRequest( final String reqType, final String urlPath, final Map<String, String> attributes, final HttpEntity body) throws IOException, IndexingConflictException { try { return getRestClient().performRequest(reqType, urlPath, attributes, body); } catch (ResponseException re) { if (re.getResponse().getStatusLine().getStatusCode() == 409) { // this is really difficult to test, and so is not throw new IndexingConflictException(re.getMessage(), re); } throw new IOException(re.getMessage(), re); } } private StringEntity stringEntity(final String string) { try { return new StringEntity(string); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "This error can't happen, so you're obviously not seeing it.", e); } } private String getEsType(boolean fullText, Optional<String> keywordType) { if (fullText) { return "text"; } if (keywordType.get().equals("string")) { return "keyword"; //TODO CODE why? why? why? } return keywordType.get(); } private String getDataTableName() { return "data"; } private String getAccessTableName() { return "access"; } private Map<String, Object> createAccessTable() { // props = {"properties": {}, // "pguid": {"type": "keyword"}, // "prefix": {"type": "keyword"}, // "version": {"type": "integer"}, // "lastin": {"type": "integer"}, // "groups": {"type": "integer"}, // "extpub": {"type": "integer"}} Map<String, Object> props = new LinkedHashMap<>(); Map<String, Object> tmp = ImmutableMap.of("type", "keyword"); props.put("pguid", tmp); tmp = ImmutableMap.of("type", "keyword"); props.put("prefix", tmp); tmp = ImmutableMap.of("type", "integer"); props.put("version", tmp); tmp = ImmutableMap.of("type", "integer"); props.put("lastin", tmp); tmp = ImmutableMap.of("type", "integer"); props.put("groups", tmp); // List of external workspaces containing DataPalette pointing to this object // This is the way to check how many public workspaces (external comparing to // home workspace of an object) have DataPalettes referencing given object (and // version). If this number is 0 then object+version is not visible as public // through DataPalettes. If it's >0 (which is the same as existence of keywords // in 'extpub') then it's visible. tmp = ImmutableMap.of("type", "integer"); props.put("extpub", tmp); // mappings = {"access": {}} Map<String, Object> table = ImmutableMap.of("properties", ImmutableMap.copyOf(props)); String tableName = getAccessTableName(); Map<String, Object> mappings = ImmutableMap.of(tableName, table); return mappings; } private void createTables(String indexName, List<IndexingRules> indexingRules) throws IOException { Map<String, Object> props = new LinkedHashMap<>(); final Map<String, Object> keyword = ImmutableMap.of("type", "keyword"); final ImmutableMap<String, String> integer = ImmutableMap.of("type", "integer"); final ImmutableMap<String, Object> bool = ImmutableMap.of("type", "boolean"); props.put("guid", keyword); props.put(SEARCH_OBJ_TYPE, keyword); props.put(SEARCH_OBJ_TYPE_VER, integer); props.put(SOURCE_TAGS, keyword); props.put(OBJ_NAME, ImmutableMap.of("type", "text")); props.put(OBJ_CREATOR, keyword); props.put(OBJ_COPIER, keyword); props.put(OBJ_PROV_MODULE, keyword); props.put(OBJ_PROV_METHOD, keyword); props.put(OBJ_PROV_MODULE_VERSION, keyword); props.put(OBJ_PROV_COMMIT_HASH, keyword); props.put(OBJ_MD5, keyword); props.put(OBJ_TIMESTAMP, ImmutableMap.of("type", "date")); props.put(OBJ_PREFIX, keyword); props.put(OBJ_STORAGE_CODE, keyword); props.put(OBJ_ACCESS_GROUP_ID, integer); props.put(OBJ_VERSION, integer); props.put(OBJ_IS_LAST, bool); props.put(OBJ_PUBLIC, bool); props.put(OBJ_SHARED, bool); props.put("ojson", ImmutableMap.of( "type", "keyword", "index", false, "doc_values", false)); props.put("pjson", ImmutableMap.of( "type", "keyword", "index", false, "doc_values", false)); for (IndexingRules rules : indexingRules) { String propName = getKeyProperty(rules.getKeyName()); String propType = getEsType(rules.isFullText(), rules.getKeywordType()); props.put(propName, ImmutableMap.of("type", propType)); } // table = {"data": {}, // "_parent": { "type": "access"}, // "properties": {"guid": {"type": "keyword"}, // {"otype": {"type": "keyword"}, // {"otypever": {"type": "integer"}, // {"oname": {"type": "text"}, // {"creator": {"type": "keyword"}, Map<String, Object> table = new LinkedHashMap<>(); table.put("_parent", ImmutableMap.of("type", getAccessTableName())); table.put("properties", ImmutableMap.copyOf(props)); // Access (parent) Map<String, Object> mappings = new LinkedHashMap<>(createAccessTable()); String tableName = getDataTableName(); mappings.put(tableName, table); Map<String, Object> doc = new LinkedHashMap<>(); doc.put("mappings", mappings); makeRequestNoConflict("PUT", "/" + indexName, doc); } public void close() throws IOException { if (restClient != null) { restClient.close(); restClient = null; } } }
package scal.io.liger.view; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.PopupWindow; import java.io.File; import java.util.ArrayList; import java.util.List; import scal.io.liger.Constants; import scal.io.liger.R; import scal.io.liger.model.Card; import scal.io.liger.model.ClipCard; import scal.io.liger.model.MediaFile; import scal.io.liger.model.OrderMediaCard; import scal.io.liger.touch.DraggableGridView; import scal.io.liger.touch.OnRearrangeListener; public class OrderMediaCardView implements DisplayableCard { public static final String TAG = "OrderMediaCardView"; private OrderMediaCard mCardModel; private Context mContext; private List<Card> mListCards = new ArrayList<Card>(); private PopupWindow mPopup; public OrderMediaCardView(Context context, Card cardModel) { mContext = context; mCardModel = (OrderMediaCard) cardModel; } @Override public View getCardView(Context context) { if (mCardModel == null) { return null; } View view = LayoutInflater.from(context).inflate(R.layout.card_order_media, null); DraggableGridView dgvOrderClips = ((DraggableGridView) view.findViewById(R.id.dgv_media_clips)); loadClips(mCardModel.getClipPaths(), dgvOrderClips); // supports automated testing view.setTag(mCardModel.getId()); return view; } public void fillList(ArrayList<String> clipPaths) { mListCards = mCardModel.getStoryPath().getCardsByIds(clipPaths); } public void loadClips(ArrayList<String> clipPaths, DraggableGridView dgvOrderClips) { dgvOrderClips.removeAllViews(); String medium = mCardModel.getMedium(); ImageView ivTemp; File fileTemp; Bitmap bmTemp; fillList(clipPaths); // removing size check and 1->3 loop, should be covered by fillList + for loop for (Card cm : mListCards) { ClipCard ccm = null; if (cm instanceof ClipCard) { ccm = (ClipCard) cm; } else { continue; } String mediaPath = null; MediaFile mf = ccm.getSelectedMediaFile(); if (mf == null) { Log.e(TAG, "no media file was found"); } else { mediaPath = mf.getPath(); } //File mediaFile = null; Uri mediaURI = null; if(mediaPath != null) { /* mediaFile = MediaHelper.loadFileFromPath(ccm.getStoryPath().buildPath(mediaPath)); if(mediaFile.exists() && !mediaFile.isDirectory()) { mediaURI = Uri.parse(mediaFile.getPath()); } */ mediaURI = Uri.parse(mediaPath); } if (medium != null && mediaURI != null) { if (medium.equals(Constants.VIDEO)) { ivTemp = new ImageView(mContext); //Bitmap videoFrame = Utility.getFrameFromVideo(mediaURI.getPath()); Bitmap videoFrame = mf.getThumbnail(); if(null != videoFrame) { ivTemp.setImageBitmap(videoFrame); } dgvOrderClips.addView(ivTemp); continue; }else if (medium.equals(Constants.PHOTO)) { ivTemp = new ImageView(mContext); ivTemp.setImageURI(mediaURI); dgvOrderClips.addView(ivTemp); continue; } } //handle fall-through cases: (media==null || medium==AUDIO) ivTemp = new ImageView(mContext); String clipType = ccm.getClipType(); int drawable = R.drawable.ic_launcher; if (clipType.equals(Constants.CHARACTER)) { drawable = R.drawable.cliptype_close; } else if (clipType.equals(Constants.ACTION)) { drawable = R.drawable.cliptype_medium; } else if (clipType.equals(Constants.RESULT)){ drawable = R.drawable.cliptype_long; } ivTemp.setImageDrawable(mContext.getResources().getDrawable(drawable)); dgvOrderClips.addView(ivTemp); } dgvOrderClips.setOnRearrangeListener(new OnRearrangeListener() { @Override public void onRearrange(int currentIndex, int newIndex) { //update actual card list Card currentCard = mListCards.get(currentIndex); int currentCardIndex = mCardModel.getStoryPath().getCardIndex(currentCard); int newCardIndex = currentCardIndex - (currentIndex - newIndex); mCardModel.getStoryPath().rearrangeCards(currentCardIndex, newCardIndex); } }); dgvOrderClips.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Unsafe Cast Util.showOrderMediaPopup(((Activity) view.getContext()), mCardModel.getMedium(), mListCards); } }); } }
package net.qiujuer.genius.util; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.telephony.TelephonyManager; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; public final class ToolUtils { /** * Sleep time * Don't throw an InterruptedException exception * * @param time long time */ public static void sleepIgnoreInterrupt(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Copy file to file * * @param source Source File * @param target Target File * @return isCopy ok */ public static boolean copyFile(File source, File target) { boolean bFlag = false; FileInputStream in = null; FileOutputStream out = null; try { if (!target.exists()) { boolean createSuccess = target.createNewFile(); if (!createSuccess) { return false; } } in = new FileInputStream(source); out = new FileOutputStream(target); byte[] buffer = new byte[8 * 1024]; int count; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } bFlag = true; } catch (Exception e) { e.printStackTrace(); bFlag = false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return bFlag; } /** * Equipment is started for the first time the generated number * Are potential "9774d56d682e549c" * * @param context Context * @return Number */ public static String getAndroidId(Context context) { return android.provider.Settings.System.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); } /** * This device's SN * * @return SerialNumber */ public static String getSerialNumber() { String serialNumber = android.os.Build.SERIAL; if ((serialNumber == null || serialNumber.length() == 0 || serialNumber.contains("unknown"))) { String[] keys = new String[]{"ro.boot.serialno", "ro.serialno"}; for (String key : keys) { try { Method systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class); serialNumber = (String) systemProperties_get.invoke(null, key); if (serialNumber != null && serialNumber.length() > 0 && !serialNumber.contains("unknown")) break; } catch (Exception e) { e.printStackTrace(); } } } return serialNumber; } public static String getDeviceId(Context context) { return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); } /** * The system contains specified App packageName * * @param context Context * @param packageName App packageName * @return isAvailable */ public static boolean isAvailablePackage(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager(); List<PackageInfo> infoList = packageManager.getInstalledPackages(0); for (PackageInfo info : infoList) { if (info.packageName.equalsIgnoreCase(packageName)) return true; } return false; } }
package com.nisoft.instools; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.nisoft.instools.bean.MaterialInspectRecode; import com.nisoft.instools.jdbc.JDBCUtil; import com.nisoft.instools.utils.StringsUtil; /** * Servlet implementation class MaterialInspectServlet */ @WebServlet("/MaterialInspectServlet") public class MaterialInspectServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MaterialInspectServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String intent = request.getParameter("intent"); String type = request.getParameter("type"); switch (intent) { case "new": String newNum = getNewJobNum(type); if(newNum!=null){ MaterialInspectRecode newRecode = new MaterialInspectRecode(); newRecode.setJobNum(newNum); newRecode.setType(type); update(newRecode); } out.write(newNum); break; case "query": ArrayList<String> joblist = queryAll(type); out.write(joblist.toString()); break; case "recoding": String job_id = request.getParameter("job_id"); MaterialInspectRecode recode = queryJobWithId(job_id); Gson gson = new Gson(); out.write(gson.toJson(recode)); break; case "jub_num": String job_num = request.getParameter("job_id"); MaterialInspectRecode recode1 = queryJobWithId(job_num); if (recode1 == null) { out.write("false"); } else { out.write("true"); } break; case "upload": String jobJson = request.getParameter("job_json"); Gson gson1 = new Gson(); MaterialInspectRecode jobRecode = gson1.fromJson(jobJson, MaterialInspectRecode.class); String picFolderPath = ""; jobRecode.setPicFolderPath(picFolderPath); int row = update(jobRecode); if (row==1){ out.write("OK"); }else{ out.write(""); } break; case "changeId": String newId = request.getParameter("newId"); String oldId = request.getParameter("oldId"); int changedRow = changeJobId(newId,oldId); if(changedRow == 1){ out.write("OK"); }else{ out.write("failed"); } break; } out.close(); } private int changeJobId(String newId,String oldId) { String sql = "update job_material_inspect set job_id = '"+newId+"' where job_id = '" +oldId+"'"; Connection conn = JDBCUtil.getConnection(); Statement st = null; int row = -1; try { st = conn.createStatement(); row = st.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } finally { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return row; } private String getNewJobNum(String type) { String number = null; String sql = "select * from job_material_inspect where job_type = '" + type + "' order by job_id"; Connection conn = JDBCUtil.getConnection(); Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); rs = st.executeQuery(sql); rs.last(); int row = rs.getRow(); String job_id = null; String[] strsJobId = null; int num = 0; Date date = new Date(); String fomatDate = StringsUtil.dateFormatForNum(date); String[] strsDate = fomatDate.split("-"); if(row>0){ job_id = rs.getString("job_id"); strsJobId = job_id.split("-"); num = Integer.parseInt(strsJobId[strsJobId.length - 1]) + 1; } switch (type) { case "": if(job_id!=null&&strsDate[0].equals(strsJobId[0])){ number = strsDate[0] + "-" + num; }else { number = strsDate[0] + "-" + 5001; } break; case "": if (job_id!=null&&strsDate[0].equals(strsJobId[0])) { number = strsDate[0] + "-" + num; } else { number = strsDate[0] + "-" + 1; } break; case "": if (job_id!=null&&strsDate[0].equals(strsJobId[0]) && strsDate[1].equals(strsJobId[1])) { number = strsDate[0] + "-" + strsDate[1] + "-" + num; } else { number = strsDate[0] + "-" + strsDate[1] + "-" + 1; } break; case "": break; } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return number; } private ArrayList<String> queryAll(String type) { ArrayList<String> allJobs = null; String sql = "select * from job_material_inspect where job_type = '" + type + "' order by job_id"; Connection conn = JDBCUtil.getConnection(); Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); rs = st.executeQuery(sql); rs.beforeFirst(); allJobs = new ArrayList<>(); while (rs.next()) { allJobs.add(rs.getString("job_id")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return allJobs; } private MaterialInspectRecode queryJobWithId(String job_id) { MaterialInspectRecode job = null; String sql = "select * from material_inspect where job_id = '" + job_id + "'"; Connection conn = JDBCUtil.getConnection(); Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); rs = st.executeQuery(sql); rs.last(); int row = rs.getRow(); if (row == 1) { job = new MaterialInspectRecode(); job.setJobNum(rs.getString("job_id")); job.setType(rs.getString("type")); job.setDescription(rs.getString("description")); job.setDate(new Date(rs.getLong("date"))); job.setInspectorId("inspector_id"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return job; } private int update(MaterialInspectRecode recode) { // String job_id = recode.getJobNum(); // String job_type = recode.getType(); // String folder = recode.getPicFolderPath(); // String description = recode.getDescription(); // String inspector_id = recode.getInspectorId(); Date date = recode.getDate(); if(date == null){ date = new Date(); } long dateTime = date.getTime(); String insertSql = "insert into job_material_inspect" + "(job_id,job_type,folder,description,inspector_id,date)values('" + recode.getJobNum() + "','" + recode.getType() + "','" + recode.getPicFolderPath() + "','" + recode.getDescription() + "','" + recode.getInspectorId() + "','" + dateTime + "') on duplicate key update job_type = values(job_type),folder=values(folder)," + "description = values(description),inspector_id = values(inspector_id)," + "date = values(date)"; Connection conn = JDBCUtil.getConnection(); Statement st = null; int row = -1; try { st = conn.createStatement(); row = st.executeUpdate(insertSql); } catch (SQLException e) { e.printStackTrace(); } finally { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return row; } }
package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import org.xml.sax.*; import org.w3c.dom.*; import java.util.*; import java.io.*; import javax.servlet.http.*; public class CmsXmlTemplateEditor extends CmsWorkplaceDefault implements I_CmsConstants { protected void commitTemporaryFile(CmsObject cms, String originalFilename, String temporaryFilename) throws CmsException { CmsFile orgFile = cms.readFile(originalFilename); CmsFile tempFile = cms.readFile(temporaryFilename); orgFile.setContents(tempFile.getContents()); cms.writeFile(orgFile); Hashtable minfos = cms.readAllProperties(temporaryFilename); Enumeration keys = minfos.keys(); while(keys.hasMoreElements()) { String keyName = (String)keys.nextElement(); cms.writeProperty(originalFilename, keyName, (String)minfos.get(keyName)); } } protected String createTemporaryFile(CmsObject cms, CmsResource file) throws CmsException { String temporaryFilename = file.getPath() + C_TEMP_PREFIX + file.getName(); // This is the code for single temporary files. // re-activate it, if the cms object provides a special // method for managing temporary files /* try { cms.copyFile(file.getAbsolutePath(), temporaryFilename); } catch(CmsException e) { if(e.getType() == e.C_FILE_EXISTS) { throwException("Temporary file for " + file.getName() + " already exists!", e.C_FILE_EXISTS); } else { throwException("Could not cread temporary file for " + file.getName() + ".", e); } }*/ // TODO: check, if this is needed: CmsResource tempFile = null; String extendedTempFile = null; boolean ok = true; try { cms.copyFile(file.getAbsolutePath(), temporaryFilename); cms.chmod(temporaryFilename, 91); } catch(CmsException e) { if((e.getType() != e.C_FILE_EXISTS) && (e.getType() != e.C_SQL_ERROR)) { // This was no file exists exception. // Vary bad. We should not go on here since we may run // in an endless loop. throw e; } ok = false; } extendedTempFile = temporaryFilename; int loop = 0; while(!ok) { ok = true; extendedTempFile = temporaryFilename + loop; try { cms.copyFile(file.getAbsolutePath(), extendedTempFile); cms.chmod(extendedTempFile, 91); } catch(CmsException e) { if((e.getType() != e.C_FILE_EXISTS) && (e.getType() != e.C_SQL_ERROR)) { // This was no file exists exception. // Vary bad. We should not go on here since we may run // in an endless loop. throw e; } // temp file could not be created loop++; ok = false; } } // Oh. we have found a temporary file. temporaryFilename = extendedTempFile; return temporaryFilename; } public Integer getAvailableTemplates(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { CmsXmlWpConfigFile configFile = getConfigFile(cms); String templatePath = configFile.getCommonTemplatePath(); Vector allTemplateFiles = cms.getFilesInFolder(templatePath); String currentTemplate = (String)parameters.get("template"); int currentTemplateIndex = 0; int currentIndex = 0; int numTemplates = allTemplateFiles.size(); for(int i = 0;i < numTemplates;i++) { CmsResource file = (CmsResource)allTemplateFiles.elementAt(i); if(file.getState() != C_STATE_DELETED) { // TODO: check, if this is needed: String filename = file.getName(); String title = cms.readProperty(file.getAbsolutePath(), C_PROPERTY_TITLE); if(title == null || "".equals(title)) { title = file.getName(); } values.addElement(file.getAbsolutePath()); names.addElement(title); if(currentTemplate.equals(file.getAbsolutePath()) || currentTemplate.equals(file.getName())) { currentTemplateIndex = currentIndex; } currentIndex++; } } return new Integer(currentTemplateIndex); } /** * Gets all views available in the workplace screen. * <P> * The given vectors <code>names</code> and <code>values</code> will * be filled with the appropriate information to be used for building * a select box. * <P> * <code>names</code> will contain language specific view descriptions * and <code>values</code> will contain the correspondig URL for each * of these views after returning from this method. * <P> * * @param cms CmsObject Object for accessing system resources. * @param lang reference to the currently valid language file * @param names Vector to be filled with the appropriate values in this method. * @param values Vector to be filled with the appropriate values in this method. * @param parameters Hashtable containing all user parameters <em>(not used here)</em>. * @return Index representing the user's current workplace view in the vectors. * @exception CmsException */ public Integer getBodys(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String currentBodySection = (String)parameters.get("body"); String bodyClassName = (String)parameters.get("bodyclass"); String tempBodyFilename = (String)session.getValue("te_tempbodyfile"); Object tempObj = CmsTemplateClassManager.getClassInstance(cms, bodyClassName); CmsXmlTemplate bodyElementClassObject = (CmsXmlTemplate)tempObj; CmsXmlTemplateFile bodyTemplateFile = bodyElementClassObject.getOwnTemplateFile(cms, tempBodyFilename, C_BODY_ELEMENT, parameters, null); Vector allBodys = bodyTemplateFile.getAllSections(); int loop = 0; int currentBodySectionIndex = 0; int numBodys = allBodys.size(); for(int i = 0;i < numBodys;i++) { String bodyname = (String)allBodys.elementAt(i); String encodedBodyname = makeHtmlEntities(bodyname); if(bodyname.equals(currentBodySection)) { currentBodySectionIndex = loop; } values.addElement(encodedBodyname); names.addElement(encodedBodyname); loop++; } return new Integer(currentBodySectionIndex); } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { CmsRequestContext reqCont = cms.getRequestContext(); HttpServletRequest orgReq = (HttpServletRequest)reqCont.getRequest().getOriginalRequest(); I_CmsSession session = cms.getRequestContext().getSession(true); // TODO: check, if this is neede: CmsFile editFile = null; // Get the user's browser String browser = orgReq.getHeader("user-agent"); String hostName = orgReq.getScheme() + "://" + orgReq.getHeader("HOST"); Encoder encoder = new Encoder(); // Get all URL parameters String content = (String)parameters.get(C_PARA_CONTENT); String body = (String)parameters.get("body"); String file = (String)parameters.get(C_PARA_FILE); String editor = (String)parameters.get("editor"); String title = (String)parameters.get(C_PARA_TITLE); String bodytitle = (String)parameters.get("bodytitle"); String layoutTemplateFilename = (String)parameters.get("template"); String bodyElementClassName = (String)parameters.get("bodyclass"); String bodyElementFilename = (String)parameters.get("bodyfile"); String action = (String)parameters.get(C_PARA_ACTION); // Get all session parameters String oldEdit = (String)session.getValue("te_oldedit"); // TODO: check, if this is neede: String bodytag = (String)session.getValue("bodytag"); String oldLayoutFilename = (String)session.getValue("te_oldlayout"); String oldTitle = (String)session.getValue("te_title"); String oldBody = (String)session.getValue("te_oldbody"); String oldBodytitle = (String)session.getValue("te_oldbodytitle"); String layoutTemplateClassName = (String)session.getValue("te_templateclass"); String tempPageFilename = (String)session.getValue("te_temppagefile"); String tempBodyFilename = (String)session.getValue("te_tempbodyfile"); String style = (String)session.getValue("te_stylesheet"); //boolean existsContentParam = (content!=null && (!"".equals(content))); boolean existsContentParam = content != null; boolean existsFileParam = (file != null && (!"".equals(file))); boolean saveRequested = ((action != null) && (C_EDIT_ACTION_SAVE.equals(action) || C_EDIT_ACTION_SAVEEXIT.equals(action))); boolean exitRequested = ((action != null) && (C_EDIT_ACTION_EXIT.equals(action) || C_EDIT_ACTION_SAVEEXIT.equals(action))); boolean bodychangeRequested = ((oldBody != null) && (body != null) && (!(oldBody.equals(body)))); boolean templatechangeRequested = (oldLayoutFilename != null && layoutTemplateFilename != null && (!(oldLayoutFilename.equals(layoutTemplateFilename)))); boolean titlechangeRequested = (oldTitle != null && title != null && (!(oldTitle.equals(title)))); boolean newbodyRequested = ((action != null) && "newbody".equals(action)); boolean previewRequested = ((action != null) && "preview".equals(action)); boolean bodytitlechangeRequested = (oldBodytitle != null && bodytitle != null && (!(oldBodytitle.equals(bodytitle)))); // Check if there is a file parameter in the request if(!existsFileParam) { throwException("No \"file\" parameter given. Don't know which file should be edited."); } // If there is no content parameter this seems to be // a new request of the page editor. // So we have to read all files and set some initial values. if(!existsContentParam) { CmsXmlControlFile originalControlFile = new CmsXmlControlFile(cms, file); if(originalControlFile.isElementClassDefined(C_BODY_ELEMENT)) { bodyElementClassName = originalControlFile.getElementClass(C_BODY_ELEMENT); } if(originalControlFile.isElementTemplateDefined(C_BODY_ELEMENT)) { bodyElementFilename = originalControlFile.getElementTemplate(C_BODY_ELEMENT); } if((bodyElementClassName == null) || (bodyElementFilename == null)) { // Either the template class or the template file // for the body element could not be determined. // BUG: Send error here } // Check, if the selected page file is locked CmsResource pageFileResource = cms.readFileHeader(file); if(!pageFileResource.isLocked()) { // BUG: Check only, dont't lock here! cms.lockResource(file); } // The content file must be locked before editing CmsResource contentFileResource = cms.readFileHeader(bodyElementFilename); if(!contentFileResource.isLocked()) { cms.lockResource(bodyElementFilename); } // Now get the currently selected master template file layoutTemplateFilename = originalControlFile.getMasterTemplate(); layoutTemplateClassName = originalControlFile.getTemplateClass(); int browserId; if(browser.indexOf("MSIE") > -1) { browserId = 0; } else { browserId = 1; } if(editor == null || "".equals(editor)) { editor = this.C_SELECTBOX_EDITORVIEWS[C_SELECTBOX_EDITORVIEWS_DEFAULT[browserId]]; session.putValue("te_pageeditor", editor); parameters.put("editor", editor); } // And finally the document title title = cms.readProperty(file, C_PROPERTY_TITLE); if(title == null) { title = ""; } // We don't want the user to go on and create any temporary // files, if he has insufficient rights. Check this now. if(!cms.accessWrite(file)) { throw new CmsException(getClassName() + "Insufficient rights for editing the file " + file, CmsException.C_NO_ACCESS); } if(!cms.accessWrite(bodyElementFilename)) { throw new CmsException(getClassName() + "Insufficient rights for editing the file " + bodyElementFilename, CmsException.C_NO_ACCESS); } // Okay. All values are initialized. Now we can create // the temporary files. tempPageFilename = createTemporaryFile(cms, pageFileResource); tempBodyFilename = createTemporaryFile(cms, contentFileResource); session.putValue("te_temppagefile", tempPageFilename); session.putValue("te_tempbodyfile", tempBodyFilename); } // Get the XML parsed content of the layout file. // This can be done by calling the getOwnTemplateFile() method of the // layout's template class. // The content is needed to determine the HTML style of the body element. Object tempObj = CmsTemplateClassManager.getClassInstance(cms, layoutTemplateClassName); CmsXmlTemplate layoutTemplateClassObject = (CmsXmlTemplate)tempObj; CmsXmlTemplateFile layoutTemplateFile = layoutTemplateClassObject.getOwnTemplateFile(cms, layoutTemplateFilename, null, parameters, null); // Get the XML parsed content of the body file. // This can be done by calling the getOwnTemplateFile() method of the // body's template class. tempObj = CmsTemplateClassManager.getClassInstance(cms, bodyElementClassName); CmsXmlTemplate bodyElementClassObject = (CmsXmlTemplate)tempObj; CmsXmlTemplateFile bodyTemplateFile = bodyElementClassObject.getOwnTemplateFile(cms, tempBodyFilename, C_BODY_ELEMENT, parameters, null); // Get the temporary page file object CmsXmlControlFile temporaryControlFile = new CmsXmlControlFile(cms, tempPageFilename); if(!existsContentParam) { Vector allBodys = bodyTemplateFile.getAllSections(); if(allBodys == null || allBodys.size() == 0) { body = ""; } else { body = (String)allBodys.elementAt(0); } // bodytitle = bodyTemplateFile.getSectionTitle(body); bodytitle = body.equals("(default)") ? "" : body; temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); temporaryControlFile.setElementTemplate(C_BODY_ELEMENT, tempBodyFilename); temporaryControlFile.write(); try { style = getStylesheet(cms, null, layoutTemplateFile, null); if(style != null && !"".equals(style)) { style = hostName + style; } } catch(Exception e) { style = ""; } session.putValue("te_stylesheet", style); } else { // There exists a content parameter. // We have to check all possible changes requested by the user. if(titlechangeRequested) { // The user entered a new document title try { cms.writeProperty(tempPageFilename, C_PROPERTY_TITLE, title); } catch(CmsException e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "Could not write property " + C_PROPERTY_TITLE + " for file " + file + "."); A_OpenCms.log(C_OPENCMS_INFO, getClassName() + e); } } } if(templatechangeRequested) { // The user requested a change of the layout template temporaryControlFile.setMasterTemplate(layoutTemplateFilename); //temporaryControlFile.write(); try { style = getStylesheet(cms, null, layoutTemplateFile, null); if(style != null && !"".equals(style)) { style = hostName + style; } } catch(Exception e) { style = ""; } session.putValue("te_stylesheet", style); } if(bodytitlechangeRequested) { // The user entered a new title for the current body //bodyTemplateFile.setSectionTitle(oldBody, bodytitle); if((!oldBody.equals("(default)")) && (!oldBody.equals("script"))) { if(bodytitle.toLowerCase().equals("script")) { bodytitle = "script"; } try { bodyTemplateFile.renameSection(oldBody, bodytitle); oldBody = bodytitle; if(!bodychangeRequested) { body = bodytitle; } } catch(Exception e) { bodytitle = oldBodytitle; } if(bodytitle.equals("script")) { session.putValue("te_pageeditor", editor); editor = C_SELECTBOX_EDITORVIEWS[1]; parameters.put("editor", editor); } } else { bodytitle = oldBodytitle; } } if(bodychangeRequested) { temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); //temporaryControlFile.write(); ////bodytitle = bodyTemplateFile.getSectionTitle(body); bodytitle = body.equals("(default)") ? "" : body; if(body.equals("script")) { // User wants to edit javascript code // Select text editor session.putValue("te_pageeditor", editor); editor = C_SELECTBOX_EDITORVIEWS[1]; parameters.put("editor", editor); } else { if(oldBody.equals("script")) { // User wants to switch back from javascript mode // Select old editor editor = (String)session.getValue("te_pageeditor"); parameters.put("editor", editor); } } } if(newbodyRequested) { body = C_BODY_ELEMENT + bodyTemplateFile.createNewSection(C_BODY_ELEMENT); bodytitle = body; temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); temporaryControlFile.setElementTemplate(C_BODY_ELEMENT, tempBodyFilename); //temporaryControlFile.write(); //bodyTemplateFile.write(); } // save file contents to our temporary file. content = encoder.unescape(content); // TODO: Set correct error page here //try { if((!exitRequested) || saveRequested) { bodyTemplateFile.setEditedTemplateContent(content, oldBody, oldEdit.equals(C_SELECTBOX_EDITORVIEWS[0])); } /*} catch(CmsException e) { if(e.getType() == e.C_XML_PARSING_ERROR) { CmsXmlWpTemplateFile errorTemplate = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms, templateFile, elementName, parameters, "parseerror"); errorTemplate.setData("details", Utils.getStackTrace(e)); return startProcessing(cms, errorTemplate, elementName, parameters, "parseerror"); } else throw e; }*/ bodyTemplateFile.write(); temporaryControlFile.write(); } // If the user requested a preview then send a redirect // to the temporary page file. if(previewRequested) { preview(tempPageFilename, reqCont); return "".getBytes(); } // If the user requested a "save" expilitly by pressing one of // the "save" buttons, copy all informations of the temporary // files to the original files. if(saveRequested) { commitTemporaryFile(cms, bodyElementFilename, tempBodyFilename); title = cms.readProperty(tempPageFilename, C_PROPERTY_TITLE); if(title != null && !"".equals(title)) { cms.writeProperty(file, C_PROPERTY_TITLE, title); } CmsXmlControlFile originalControlFile = new CmsXmlControlFile(cms, file); originalControlFile.setMasterTemplate(temporaryControlFile.getMasterTemplate()); originalControlFile.write(); } // Check if we should leave th editor instead of start processing if(exitRequested) { // First delete temporary files temporaryControlFile.removeFromFileCache(); bodyTemplateFile.removeFromFileCache(); cms.deleteFile(tempBodyFilename); cms.deleteFile(tempPageFilename); try { cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceMainPath()); } catch(IOException e) { throwException("Could not send redirect to workplace main screen.", e); } //return "".getBytes(); return null; } // Include the datablocks of the layout file into the body file. // So the "bodytag" and "style" data can be accessed by the body file. Element bodyTag = layoutTemplateFile.getBodyTag(); bodyTemplateFile.setBodyTag(bodyTag); // Load the body! content = bodyTemplateFile.getEditableTemplateContent(this, parameters, body, editor.equals(C_SELECTBOX_EDITORVIEWS[0]), style); content = encoder.escapeWBlanks(content); parameters.put(C_PARA_CONTENT, content); // put the body parameter so that the selectbox can set the correct current value parameters.put("body", body); parameters.put("bodyfile", bodyElementFilename); parameters.put("bodyclass", bodyElementClassName); parameters.put("template", layoutTemplateFilename); // remove all parameters that could be relevant for the // included editor. parameters.remove(C_PARA_FILE); parameters.remove(C_PARA_ACTION); int numEditors = C_SELECTBOX_EDITORVIEWS.length; for(int i = 0;i < numEditors;i++) { if(editor.equals(C_SELECTBOX_EDITORVIEWS[i])) { parameters.put("editor._CLASS_", C_SELECTBOX_EDITORVIEWS_CLASSES[i]); parameters.put("editor._TEMPLATE_", getConfigFile(cms).getWorkplaceTemplatePath() + C_SELECTBOX_EDITORVIEWS_TEMPLATES[i]); } } session.putValue("te_oldedit", editor); session.putValue("te_oldbody", body); session.putValue("te_oldbodytitle", bodytitle); session.putValue("te_oldlayout", layoutTemplateFilename); if(title != null) { session.putValue("te_title", title); } else { session.putValue("te_title", ""); } session.putValue("te_templateclass", layoutTemplateClassName); CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); xmlTemplateDocument.setData("editor", editor); xmlTemplateDocument.setData("bodyfile", bodyElementFilename); xmlTemplateDocument.setData("bodyclass", bodyElementClassName); xmlTemplateDocument.setData("editorframe", (String)parameters.get("root.editorframe")); // Put the "file" datablock for processing in the template file. // It will be inserted in a hidden input field and given back when submitting. xmlTemplateDocument.setData(C_PARA_FILE, file); return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** Gets all editor views available in the template editor screens. * <P> * The given vectors <code>names</code> and <code>values</code> will * be filled with the appropriate information to be used for building * a select box. * <P> * Used to build font select boxes in editors. * * @param cms CmsObject Object for accessing system resources. * @param lang reference to the currently valid language file * @param names Vector to be filled with the appropriate values in this method. * @param values Vector to be filled with the appropriate values in this method. * @param parameters Hashtable containing all user parameters <em>(not used here)</em>. * @return Index representing the user's current workplace view in the vectors. * @exception CmsException */ public Integer getEditorViews(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Vector names2 = new Vector(); Vector values2 = new Vector(); getConstantSelectEntries(names2, values2, C_SELECTBOX_EDITORVIEWS, lang); int browserId; CmsRequestContext reqCont = cms.getRequestContext(); HttpServletRequest orgReq = (HttpServletRequest)reqCont.getRequest().getOriginalRequest(); String browser = orgReq.getHeader("user-agent"); if(browser.indexOf("MSIE") > -1) { browserId = 0; } else { browserId = 1; } int loop = 1; int allowedEditors = C_SELECTBOX_EDITORVIEWS_ALLOWED[browserId]; if(((String)parameters.get("body")).equals("script")) { allowedEditors = allowedEditors & 510; } for(int i = 0;i < names2.size();i++) { if((allowedEditors & loop) > 0) { values.addElement(values2.elementAt(i)); names.addElement(names2.elementAt(i)); } loop <<= 1; } int currentIndex = values.indexOf((String)parameters.get("editor")); return new Integer(currentIndex); } /** * Indicates if the results of this class are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } protected void preview(String previewPath, CmsRequestContext reqCont) throws CmsException { HttpServletRequest srvReq = (HttpServletRequest)reqCont.getRequest().getOriginalRequest(); String servletPath = srvReq.getServletPath(); try { reqCont.getResponse().sendCmsRedirect(previewPath); } catch(IOException e) { throwException("Could not send redirect preview file " + servletPath + previewPath, e); } } /** * User method to generate an URL for a preview. * The currently selected temporary file name will be considered. * <P> * In the editor template file, this method can be invoked by * <code>&lt;METHOD name="previewUrl"/&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document <em>(not used here)</em>. * @param userObj Hashtable with parameters <em>(not used here)</em>. * @return String with the pics URL. * @exception CmsException */ public Object previewUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObj) throws CmsException { CmsRequestContext reqCont = cms.getRequestContext(); String servletPath = ((HttpServletRequest)reqCont.getRequest().getOriginalRequest()).getServletPath(); I_CmsSession session = cms.getRequestContext().getSession(true); String tempPath = (String)session.getValue("te_temppagefile"); String result = servletPath + tempPath; return result; } /** * Pre-Sets the value of the body title input field. * This method is directly called by the content definiton. * @param Cms The CmsObject. * @param lang The language file. * @param parameters User parameters. * @return Value that is pre-set into the title field. * @exception CmsExeption if something goes wrong. */ public String setBodyTitle(CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String title = (String)session.getValue("te_oldbodytitle"); return makeHtmlEntities(title); } public Object setText(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObj) throws CmsException { Hashtable parameters = (Hashtable)userObj; // TODO: check, if this is needed: String filename = (String)parameters.get("file"); String content = (String)parameters.get(C_PARA_CONTENT); boolean existsContentParam = (content != null && (!"".equals(content))); // Check the existance of the "file" parameter if(!existsContentParam) { String errorMessage = getClassName() + "No content found."; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, errorMessage); } content = ""; //return("no content"); // throw new CmsException(errorMessage, CmsException.C_BAD_NAME); } // Escape the text for including it in HTML text return content; } /** * Pre-Sets the value of the title input field. * This method is directly called by the content definiton. * @param Cms The CmsObject. * @param lang The language file. * @param parameters User parameters. * @return Value that is pre-set into the title field. * @exception CmsExeption if something goes wrong. */ public String setTitle(CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String name = (String)session.getValue("te_title"); return makeHtmlEntities(name); } private String makeHtmlEntities(String s) { int idx = s.indexOf("\""); while(idx > -1) { s = s.substring(0, idx) + "&quot;" + s.substring(idx + 1); idx = s.indexOf("\""); } return s; } }
package com.simplenote.android.widget; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.simplenote.android.Constants; import com.simplenote.android.R; import com.simplenote.android.model.Note; /** * Specialized ListAdapter for converting Note objects into views based on the notes_row layout * @author bryanjswift */ public class NotesAdapter extends BaseAdapter { private static final String LOGGING_TAG = Constants.TAG + "NotesAdapter"; private final Context context; private Note[] notes; /** * Default constructor for converting Note objects to ListView rows * @param context where the notes are being viewed * @param notes to use as data */ public NotesAdapter(Context context, Note[] notes) { this.context = context; this.notes = notes; } /** * @see android.widget.Adapter#getCount() */ public int getCount() { return notes.length; } /** * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return notes[position]; } /** * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { return notes[position].getId(); } /** * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { final LinearLayout row; Log.d(LOGGING_TAG, String.format("Getting view for '%d' with title '%s'",notes[position].getId(), notes[position].getTitle())); if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(context); row = (LinearLayout) inflater.inflate(R.layout.notes_row, parent, false); } else { Log.d(LOGGING_TAG, String.format("convertView class is '%s'", convertView.getClass().getName())); row = (LinearLayout) convertView; } ((TextView) row.findViewById(R.id.text_title)).setText(notes[position].getTitle()); ((TextView) row.findViewById(R.id.text_date)).setText(notes[position].getDateModified()); return row; } /** * @return the notes */ public final Note[] getNotes() { return notes; } /** * @param notes the notes to set */ public final void setNotes(Note[] notes) { this.notes = notes; } }
package com.valkryst.VTerminal.component; import com.valkryst.VRadio.Radio; import com.valkryst.VTerminal.AsciiCharacter; import com.valkryst.VTerminal.AsciiString; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.font.Font; import com.valkryst.VTerminal.misc.IntRange; import lombok.Getter; import lombok.Setter; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Arrays; import java.util.Objects; import java.util.Optional; public class Component { /** The x-axis (column) coordinate of the top-left character. */ @Getter private int columnIndex; /** The y-axis (row) coordinate of the top-left character. */ @Getter private int rowIndex; /** The width, in characters. */ @Getter private int width; /** The height, in characters. */ @Getter private int height; /** Whether or not the component is currently the target of the user's input. */ @Getter private boolean isFocused = false; /** The bounding box. */ @Getter private Rectangle boundingBox = new Rectangle(); /** The strings representing the character-rows of the component. */ @Getter private AsciiString[] strings; /** The radio to transmit events to. */ @Getter private Radio<String> radio; /** The screen that the component is on. */ @Getter @Setter private Screen screen; /** * Constructs a new AsciiComponent. * * @param columnIndex * The x-axis (column) coordinate of the top-left character. * * @param rowIndex * The y-axis (row) coordinate of the top-left character. * * @param width * The width, in characters. * * @param height * The height, in characters. */ public Component(final int columnIndex, final int rowIndex, final int width, final int height) { if (columnIndex < 0) { throw new IllegalArgumentException("You must specify a columnIndex of 0 or greater."); } if (rowIndex < 0) { throw new IllegalArgumentException("You must specify a rowIndex of 0 or greater."); } if (width < 1) { throw new IllegalArgumentException("You must specify a width of 1 or greater."); } if (height < 1) { throw new IllegalArgumentException("You must specify a height of 1 or greater."); } this.columnIndex = columnIndex; this.rowIndex = rowIndex; this.width = width; this.height = height; boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(width, height); strings = new AsciiString[height]; for (int row = 0 ; row < height ; row++) { strings[row] = new AsciiString(width); } } @Override public boolean equals(final Object otherObj) { if (otherObj instanceof Component == false) { return false; } // Left out a check for isFocused since two components could be // virtually identical other than their focus. // Left out a check for radio. final Component otherComp = (Component) otherObj; boolean isEqual = super.equals(otherObj); isEqual &= Objects.equals(columnIndex, otherComp.getColumnIndex()); isEqual &= Objects.equals(rowIndex, otherComp.getRowIndex()); isEqual &= Objects.equals(width, otherComp.getWidth()); isEqual &= Objects.equals(height, otherComp.getHeight()); isEqual &= Objects.equals(boundingBox, otherComp.getBoundingBox()); isEqual &= Arrays.equals(strings, otherComp.getStrings()); return isEqual; } @Override public int hashCode() { return Objects.hash(columnIndex, rowIndex, width, height, boundingBox, strings); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Component:"); sb.append("\n\tColumn Index:\t").append(columnIndex); sb.append("\n\tRow Index:\t").append(rowIndex); sb.append("\n\tWidth:\t").append(width); sb.append("\n\tHeight:\t").append(height); sb.append("\n\tIs Focused:\t").append(isFocused); sb.append("\n\tBounding Box:\t" + boundingBox); sb.append("\n\tStrings:\n"); for (final AsciiString string : strings) { for (final AsciiCharacter character : string.getCharacters()) { sb.append(character.getCharacter()); } sb.append("\n\t\t"); } sb.append("\n\tRadio:\t" + radio); return sb.toString(); } /** * Registers events, required by the component, with the specified panel. * * @param panel * The panel to register events with. */ public void registerEventHandlers(final Panel panel) { final Font font = panel.getImageCache().getFont(); final int fontWidth = font.getWidth(); final int fontHeight = font.getHeight(); panel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { isFocused = intersects(e, fontWidth, fontHeight); } } @Override public void mousePressed(final MouseEvent e) {} @Override public void mouseReleased(final MouseEvent e) {} @Override public void mouseEntered(final MouseEvent e) {} @Override public void mouseExited(final MouseEvent e) {} }); } /** * Draws the component on the specified screen. * * @param screen * The screen to draw on. */ public void draw(final Screen screen) { for (int row = 0 ; row < strings.length ; row++) { screen.write(strings[row], columnIndex, rowIndex + row); } } /** Attempts to transmit a "DRAW" event to the assigned Radio. */ public void transmitDraw() { if (radio != null) { radio.transmit("DRAW"); } } /** * Determines if the specified component intersects with this component. * * @param otherComponent * The component to check intersection with. * * @return * Whether or not the components intersect. */ public boolean intersects(final Component otherComponent) { return otherComponent != null && boundingBox.intersects(otherComponent.getBoundingBox()); } /** * Determines if the specified point intersects with this component. * * @param pointX * The x-axis (column) coordinate. * * @param pointY * The y-axis (row) coordinate. * * @return * Whether or not the point intersects with this component. */ public boolean intersects(final int pointX, final int pointY) { boolean intersects = pointX >= columnIndex; intersects &= pointX < (boundingBox.getWidth() + columnIndex); intersects &= pointY >= rowIndex; intersects &= pointY < (boundingBox.getHeight() + rowIndex); return intersects; } /** * Determines whether or not the specified mouse event is at a point that intersects this component. * * @param event * The event. * * @param fontWidth * The width of the font being used to draw the component's characters. * * @param fontHeight * The height of the font being used to draw the component's characters. * * @return * Whether or not the mouse event is at a point that intersects this component. */ public boolean intersects(final MouseEvent event, final int fontWidth, final int fontHeight) { final int mouseX = event.getX() / fontWidth; final int mouseY = event.getY() / fontHeight; return intersects(mouseX, mouseY); } /** * Determines whether or not the specified position is within the bounds of the component. * * @param columnIndex * The x-axis (column) coordinate. * * @param rowIndex * The y-axis (row) coordinate. * * @return * Whether or not the specified position is within the bounds of the component. */ public boolean isPositionValid(final int columnIndex, final int rowIndex) { if (rowIndex < 0 || rowIndex > boundingBox.getHeight() - 1) { return false; } if (columnIndex < 0 || columnIndex > boundingBox.getWidth() - 1) { return false; } return true; } /** * Enables the blink effect for every character. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.enableBlinkEffect(millsBetweenBlinks, radio); } } } /** Resumes the blink effect for every character. */ public void resumeBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.resumeBlinkEffect(); } } } /** Pauses the blink effect for every character. */ public void pauseBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.pauseBlinkEffect(); } } } /** Disables the blink effect for every character. */ public void disableBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.disableBlinkEffect(); } } } /** * Retrieves the string corresponding to a row. * * @param rowIndex * The row index. * * @return * The string. */ public AsciiString getString(final int rowIndex) { return strings[rowIndex]; } /** Sets all characters to be redrawn. */ public void setAllCharactersToBeRedrawn() { for (final AsciiString string : strings) { string.setAllCharactersToBeRedrawn(); } } /** * Sets every character, on the Screen that the component * resides on, at the component's current location to be * redrawn. * * This should only be called when the component is moved * on-screen or resized. */ private void setLocationOnScreenToBeRedrawn() { for (int y = rowIndex ; y <= rowIndex + height ; y++) { screen.getString(y).setCharacterRangeToBeRedrawn(new IntRange(columnIndex, columnIndex + width)); } } /** * Retrieves the AsciiCharacter at a specific location. * * @param columnIndex * The x-axis (column) coordinate of the location. * * @param rowIndex * The y-axis (row) coordinate of the location. * * @return * The AsciiCharacter at the specified location or nothing * if the location is invalid. */ public Optional<AsciiCharacter> getCharacterAt(final int columnIndex, final int rowIndex) { if (isPositionValid(columnIndex, rowIndex)) { return Optional.of(strings[rowIndex].getCharacters()[columnIndex]); } return Optional.empty(); } /** * Sets a new value for the columnIndex. * * Does nothing if the specified columnIndex is < 0. * * @param columnIndex * The new x-axis (column) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public void setColumnIndex(final int columnIndex) { if (columnIndex >= 0) { setLocationOnScreenToBeRedrawn(); this.columnIndex = columnIndex; boundingBox.setLocation(columnIndex, rowIndex); setAllCharactersToBeRedrawn(); } } /** * Sets a new value for the rowIndex. * * Does nothing if the specified rowIndex is < 0. * * @param rowIndex * The y-axis (row) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public void setRowIndex(final int rowIndex) { if (rowIndex >= 0) { setLocationOnScreenToBeRedrawn(); this.rowIndex = rowIndex; boundingBox.setLocation(columnIndex, rowIndex); setAllCharactersToBeRedrawn(); } } /** * Sets a new value for the width. * * Does nothing if the specified width is < 0 or < columnIndex. * * @param width * The new width, in characters, of the component. * * @return * Whether or not the new value was set. */ public void setWidth(final int width) { if (width < 0 || width < columnIndex) { return; } setLocationOnScreenToBeRedrawn(); this.width = width; boundingBox.setSize(width, height); setAllCharactersToBeRedrawn(); } /** * Sets a new value for the height. * * Does nothing if the specified height is < 0 or < rowIndex. * * @param height * The new height, in characters, of the component. * * @return * Whether or not the new value was set. */ public void setHeight(final int height) { if (height < 0 || height < rowIndex) { return; } setLocationOnScreenToBeRedrawn(); this.height = height; boundingBox.setSize(width, height); setAllCharactersToBeRedrawn(); } /** * Sets a new radio. * * @param radio * The new radio. */ public void setRadio(final Radio<String> radio) { if (radio != null) { this.radio = radio; } } }
package project6867; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import net.sf.javaml.classification.Classifier; import project6867.ClassifierTrainer.ClassifierType; import project6867.ClassifierTrainer.DataType; import ch.idsia.agents.Agent; import ch.idsia.benchmark.tasks.BasicTask; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.MarioAIOptions; public final class MarioTest { private static MarioAIOptions options; private static BufferedWriter output; public static void evaluate(Agent agent) { options.setAgent(agent); final BasicTask basicTask = new BasicTask(options); //options.setVisualization(true); basicTask.doEpisodes(1, false, 1); EvaluationInfo info = basicTask.getEnvironment().getEvaluationInfo(); try { output.write("{" + options.asString() + "-ld" + + options.getLevelDifficulty() + "} " + + info.computeWeightedFitness() + ", " + info.marioStatus + "\n"); output.flush(); } catch (IOException e) { e.printStackTrace(); } System.out.println("\nEvaluationInfo: \n" + basicTask.getEnvironment().getEvaluationInfoAsString()); } public static void main(String[] args) { try{output = new BufferedWriter(new FileWriter("NB1k@.1results.txt"));}catch(IOException e){e.printStackTrace();} Classifier c = ClassifierTrainer.getClassifier(ClassifierType.NB, DataType.ONE, null); Agent agent = new MLAgent(c); String[] ops = { "-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le off -ls 98886", // no enemies, no blocks, no gaps "-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le on -ls 31646", // enemies "-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg on -le off -ls 16007", // just gaps "-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg off -le on -ls 19682", //enemies, blocks "-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg on -ls 79612"}; // enemies, blocks, gaps for(int diff = 1; diff < 10; diff++){ for(String o : ops){ options = new MarioAIOptions(args); options.setArgs(o); options.setLevelDifficulty(diff); evaluate(agent); } } try{output.close();}catch(IOException e){e.printStackTrace();} System.exit(0); } }
package com.bloatit.web.utils.url; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.bloatit.common.FatalErrorException; import com.bloatit.web.html.components.standard.HtmlLink; import com.bloatit.web.server.Context; import com.bloatit.web.server.Linkable; import com.bloatit.web.server.Session; import com.bloatit.web.utils.annotations.Loaders; import com.bloatit.web.utils.annotations.PageComponent; import com.bloatit.web.utils.annotations.PageName; import com.bloatit.web.utils.annotations.RequestParam; public class UrlBuilder { private final Map<String, Object> parameters = new HashMap<String, Object>(); private final Class<? extends Linkable> linkableClass; private final Session session; public UrlBuilder(final Linkable linkable) { linkableClass = linkable.getClass(); this.session = Context.getSession(); fillParameters(linkable, linkableClass); } public UrlBuilder(final Class<? extends Linkable> linkableClass) { super(); this.session = Context.getSession(); this.linkableClass = linkableClass; } public UrlBuilder addParameter(final String name, final Object value) { parameters.put(name, value); return this; } public String buildUrl() { final StringBuilder sb = new StringBuilder(); // find language sb.append("/").append(session.getLanguage().getCode()).append("/"); // find name if (linkableClass.getAnnotation(PageName.class) != null) { sb.append(linkableClass.getAnnotation(PageName.class).value()); } else { sb.append(linkableClass.getSimpleName().toLowerCase()); } buildUrl(sb, linkableClass); return sb.toString(); } private void buildUrl(final StringBuilder sb, final Class<?> pageClass) { for (final Field f : pageClass.getDeclaredFields()) { final RequestParam param = f.getAnnotation(RequestParam.class); if (param != null && param.role() != RequestParam.Role.POST) { final String name = param.name().equals("") ? f.getName() : param.name(); String strValue = null; final Object value = parameters.get(name); if (value != null) { strValue = Loaders.toStr(value); } else if (param.defaultValue().equals("")) { throw new FatalErrorException("Parameter " + name + " needs a value.", null); } else { strValue = param.defaultValue(); } if (!strValue.equals(param.defaultValue())) { sb.append("/").append(name).append("-").append(strValue); } } else if (f.getAnnotation(PageComponent.class) != null) { buildUrl(sb, f.getClass()); } } } public HtmlLink getHtmlLink(final String text) { return new HtmlLink(buildUrl(), text); } private void fillParameters(final Object linkable, final Class<? extends Object> linkableClass) { for (final Field f : linkableClass.getDeclaredFields()) { final RequestParam param = f.getAnnotation(RequestParam.class); try { if (param != null) { if (!f.isAccessible()) { f.setAccessible(true); } addParameter(param.name().equals("") ? f.getName() : param.name(), f.get(linkable)); } else if (f.getAnnotation(PageComponent.class) != null) { if (!f.isAccessible()) { f.setAccessible(true); } fillParameters(f.get(linkable), f.getDeclaringClass()); } } catch (final IllegalArgumentException e) { throw new FatalErrorException("Cannot parse the pageComponent", e); } catch (final IllegalAccessException e) { throw new FatalErrorException("Cannot parse the pageComponent", e); } } } }
package com.manishkprboilerplate.web_services; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; public class ClientOkHttp { static final int TIME_OUT = 120; public static OkHttpClient getOKHTTPClient(){ OkHttpClient.Builder httpClient = new OkHttpClient.Builder().readTimeout(TIME_OUT, TimeUnit.SECONDS).connectTimeout(TIME_OUT, TimeUnit.SECONDS); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(logging); httpClient.addInterceptor(new LoggingInterceptor()); OkHttpClient client = httpClient.build(); return client; } }