answer
stringlengths
17
10.2M
/** * Origin: jbox2d */ package com.almasb.gameutils.math; import com.almasb.gameutils.pool.Poolable; import java.io.Serializable; /** * A 2D column vector with float precision. * Can be used to represent a point in 2D space. * Can be used instead of JavaFX Point2D to avoid object allocations. * This is also preferred for private fields. */ public final class Vec2 implements Serializable, Poolable { private static final long serialVersionUID = 1L; public float x, y; public Vec2() { this(0, 0); } public Vec2(float x, float y) { this.x = x; this.y = y; } public Vec2(Vec2 toCopy) { this(toCopy.x, toCopy.y); } /** * Zero out this vector. */ public void setZero() { x = 0.0f; y = 0.0f; } /** * Set this vector component-wise. * * @param x x component * @param y y component * @return this vector */ public Vec2 set(float x, float y) { this.x = x; this.y = y; return this; } /** * Set this vector to another vector. * * @return this vector */ public Vec2 set(Vec2 v) { this.x = v.x; this.y = v.y; return this; } /** * Return the sum of this vector and another; does not alter either one. * * @return new vector */ public Vec2 add(Vec2 v) { return new Vec2(x + v.x, y + v.y); } /** * Return the difference of this vector and another; does not alter either one. * * @return new vector */ public Vec2 sub(Vec2 v) { return new Vec2(x - v.x, y - v.y); } /** * Return this vector multiplied by a scalar; does not alter this vector. * * @return new vector */ public Vec2 mul(float a) { return new Vec2(x * a, y * a); } /** * Return the negation of this vector; does not alter this vector. * * @return new vector */ public Vec2 negate() { return new Vec2(-x, -y); } /** * Flip the vector and return it - alters this vector. * * @return this vector */ public Vec2 negateLocal() { x = -x; y = -y; return this; } /** * Add another vector to this one and returns result - alters this vector. * * @return this vector */ public Vec2 addLocal(Vec2 v) { x += v.x; y += v.y; return this; } /** * Adds values to this vector and returns result - alters this vector. * * @return this vector */ public Vec2 addLocal(float x, float y) { this.x += x; this.y += y; return this; } /** * Subtract another vector from this one and return result - alters this vector. * * @return this vector */ public Vec2 subLocal(Vec2 v) { x -= v.x; y -= v.y; return this; } /** * Multiply this vector by a number and return result - alters this vector. * * @return this vector */ public Vec2 mulLocal(float a) { x *= a; y *= a; return this; } /** * Get the skew vector such that dot(skew_vec, other) == cross(vec, other). * * @return new vector */ public Vec2 skew() { return new Vec2(-y, x); } /** * Get the skew vector such that dot(skew_vec, other) == cross(vec, other); * does not alter this vector. * * @param out the out vector to alter */ public void skew(Vec2 out) { out.x = -y; out.y = x; } /** * @return the length of this vector */ public float length() { return GameMath.sqrt(x * x + y * y); } /** * @return the squared length of this vector */ public float lengthSquared() { return (x * x + y * y); } public float distance(float otherX, float otherY) { float dx = otherX - x; float dy = otherY - y; return (float) Math.sqrt(dx * dx + dy * dy); } public float distanceSquared(float otherX, float otherY) { float dx = otherX - x; float dy = otherY - y; return dx * dx + dy * dy; } public boolean distanceLessThanOrEqual(float otherX, float otherY, float distance) { return distanceSquared(otherX, otherY) <= distance * distance; } public boolean distanceGreaterThanOrEqual(float otherX, float otherY, float distance) { return distanceSquared(otherX, otherY) >= distance * distance; } /** * Normalize this vector and return the length before normalization. Alters this vector. */ public float normalize() { float length = length(); if (length < GameMath.EPSILON) { return 0f; } float invLength = 1.0f / length; x *= invLength; y *= invLength; return length; } /** * Normalizes and returns this vector. Alters this vector. * * @return this vector */ public Vec2 normalizeLocal() { normalize(); return this; } /** * True if the vector represents a pair of valid, non-infinite floating point numbers. */ public boolean isValid() { return !Float.isNaN(x) && !Float.isInfinite(x) && !Float.isNaN(y) && !Float.isInfinite(y); } /** * Return a new vector that has positive components. * * @return new vector */ public Vec2 abs() { return new Vec2(GameMath.abs(x), GameMath.abs(y)); } /** * Modify this vector to have only positive components. * * @return this vector */ public Vec2 absLocal() { x = GameMath.abs(x); y = GameMath.abs(y); return this; } /** * @return angle in degrees (-180, 180] between this vector and X axis (1, 0) */ public float angle() { return angle(1, 0); } /** * @param other other vector * @return angle in degrees (-180, 180] between this vector and other */ public float angle(Vec2 other) { return angle(other.x, other.y); } /** * @param otherX x component of other vector * @param otherY y component of other vector * @return angle in degrees (-180, 180] between this vector and other */ public float angle(float otherX, float otherY) { double angle1 = Math.toDegrees(Math.atan2(y, x)); double angle2 = Math.toDegrees(Math.atan2(otherY, otherX)); return (float) (angle1 - angle2); // final float ax = otherX; // final float ay = otherY; // final float delta = (ax * x + ay * y) / // (float)Math.sqrt((ax * ax + ay * ay) * (x * x + y * y)); // if (delta > 1.0) { // return 0; // if (delta < -1.0) { // return 180; // return (float) Math.toDegrees(Math.acos(delta)); } /** * @return a copy of this vector */ @SuppressWarnings("CloneDoesntCallSuperClone") @Override public Vec2 clone() { return new Vec2(x, y); } /** * @return a copy of this vector (new instance) */ public Vec2 copy() { return clone(); } @Override public String toString() { return "(" + x + "," + y + ")"; } @Override public void reset() { setZero(); } /* STATIC */ public static Vec2 abs(Vec2 a) { return new Vec2(GameMath.abs(a.x), GameMath.abs(a.y)); } public static void absToOut(Vec2 a, Vec2 out) { out.x = GameMath.abs(a.x); out.y = GameMath.abs(a.y); } public static float dot(final Vec2 a, final Vec2 b) { return a.x * b.x + a.y * b.y; } public static float cross(final Vec2 a, final Vec2 b) { return a.x * b.y - a.y * b.x; } public static Vec2 cross(Vec2 a, float s) { return new Vec2(s * a.y, -s * a.x); } public static void crossToOut(Vec2 a, float s, Vec2 out) { final float tempy = -s * a.x; out.x = s * a.y; out.y = tempy; } public static void crossToOutUnsafe(Vec2 a, float s, Vec2 out) { assert (out != a); out.x = s * a.y; out.y = -s * a.x; } public static Vec2 cross(float s, Vec2 a) { return new Vec2(-s * a.y, s * a.x); } public static void crossToOut(float s, Vec2 a, Vec2 out) { final float tempY = s * a.x; out.x = -s * a.y; out.y = tempY; } public static void crossToOutUnsafe(float s, Vec2 a, Vec2 out) { assert (out != a); out.x = -s * a.y; out.y = s * a.x; } public static void negateToOut(Vec2 a, Vec2 out) { out.x = -a.x; out.y = -a.y; } public static Vec2 min(Vec2 a, Vec2 b) { return new Vec2(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y); } public static Vec2 max(Vec2 a, Vec2 b) { return new Vec2(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y); } public static void minToOut(Vec2 a, Vec2 b, Vec2 out) { out.x = a.x < b.x ? a.x : b.x; out.y = a.y < b.y ? a.y : b.y; } public static void maxToOut(Vec2 a, Vec2 b, Vec2 out) { out.x = a.x > b.x ? a.x : b.x; out.y = a.y > b.y ? a.y : b.y; } /** * @see Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(x); result = prime * result + Float.floatToIntBits(y); return result; } /** * @see Object#equals(Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vec2 other = (Vec2) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; return true; } }
package s04physics; import com.almasb.fxgl.app.ApplicationMode; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.entity.Entities; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; import com.almasb.fxgl.input.UserAction; import com.almasb.fxgl.physics.BoundingShape; import com.almasb.fxgl.physics.HitBox; import com.almasb.fxgl.physics.PhysicsComponent; import com.almasb.fxgl.physics.box2d.dynamics.BodyType; import com.almasb.fxgl.settings.GameSettings; import javafx.geometry.Point2D; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; /** * Sample that shows how to use ChainShape for platforms. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public class PlatformerSample extends GameApplication { private Entity player; @Override protected void initSettings(GameSettings settings) { settings.setWidth(800); settings.setHeight(600); settings.setTitle("PlatformerSample"); settings.setVersion("0.1"); settings.setFullScreen(false); settings.setIntroEnabled(false); settings.setMenuEnabled(false); settings.setProfilingEnabled(false); settings.setApplicationMode(ApplicationMode.DEVELOPER); } @Override protected void initInput() { Input input = getInput(); input.addAction(new UserAction("Left") { @Override protected void onActionBegin() { player.getComponent(PhysicsComponent.class).setLinearVelocity(new Point2D(-200, 0)); } }, KeyCode.A); input.addAction(new UserAction("Right") { @Override protected void onActionBegin() { player.getComponent(PhysicsComponent.class).setLinearVelocity(new Point2D(200, 0)); } }, KeyCode.D); input.addAction(new UserAction("Jump") { @Override protected void onActionBegin() { PhysicsComponent physics = player.getComponent(PhysicsComponent.class); if (physics.isGrounded()) { double dx = physics.getLinearVelocity().getX(); physics.setLinearVelocity(new Point2D(dx, -100)); } } }, KeyCode.W); input.addAction(new UserAction("Grow") { @Override protected void onActionBegin() { double x = player.getX(); double y = player.getY(); player.removeFromWorld(); player = createPlayer(x, y, 60, 80); } }, KeyCode.SPACE); } @Override protected void initGame() { createPlatforms(); player = createPlayer(100, 100, 40, 60); } private void createPlatforms() { Entities.builder() .at(0, 500) .viewFromNode(new Rectangle(120, 100, Color.GRAY)) .bbox(new HitBox("Main", BoundingShape.chain( new Point2D(0, 0), new Point2D(120, 0), new Point2D(120, 100), new Point2D(0, 100) ))) .with(new PhysicsComponent()) .buildAndAttach(getGameWorld()); Entities.builder() .at(180, 500) .viewFromNode(new Rectangle(400, 100, Color.GRAY)) .bbox(new HitBox("Main", BoundingShape.chain( new Point2D(0, 0), new Point2D(400, 0), new Point2D(400, 100), new Point2D(0, 100) ))) .with(new PhysicsComponent()) .buildAndAttach(getGameWorld()); } private Entity createPlayer(double x, double y, double width, double height) { PhysicsComponent physics = new PhysicsComponent(); physics.setGenerateGroundSensor(true); physics.setBodyType(BodyType.DYNAMIC); return Entities.builder() .at(x, y) .viewFromNodeWithBBox(new Rectangle(width, height, Color.BLUE)) .with(physics) .buildAndAttach(getGameWorld()); } public static void main(String[] args) { launch(args); } }
package com.continuuity.gateway; import com.continuuity.api.common.Bytes; import com.continuuity.api.data.OperationResult; import com.continuuity.api.flow.flowlet.StreamEvent; import com.continuuity.app.Id; import com.continuuity.app.queue.QueueName; import com.continuuity.data.operation.Operation; import com.continuuity.data.operation.OperationContext; import com.continuuity.data.operation.Read; import com.continuuity.data.operation.Write; import com.continuuity.data.operation.WriteOperation; import com.continuuity.data.operation.executor.OperationExecutor; import com.continuuity.data.operation.ttqueue.DequeueResult; import com.continuuity.data.operation.ttqueue.QueueAck; import com.continuuity.data.operation.ttqueue.QueueConfig; import com.continuuity.data.operation.ttqueue.QueueConsumer; import com.continuuity.data.operation.ttqueue.QueueDequeue; import com.continuuity.data.operation.ttqueue.QueueEntryPointer; import com.continuuity.data.operation.ttqueue.QueuePartitioner; import com.continuuity.data.operation.ttqueue.admin.QueueConfigure; import com.continuuity.gateway.auth.GatewayAuthenticator; import com.continuuity.streamevent.StreamEventCodec; import org.apache.flume.EventDeliveryException; import org.apache.flume.api.RpcClient; import org.apache.flume.api.RpcClientFactory; import org.apache.flume.event.SimpleEvent; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestUtil { private static final Logger LOG = LoggerFactory.getLogger(TestUtil.class); private static String apiKey = null; public static final String DEFAULT_ACCOUNT_ID = com.continuuity.data.Constants.DEVELOPER_ACCOUNT_ID; /** defaults to be used everywhere where we don't have authenticated accounts */ public static final OperationContext DEFAULT_CONTEXT = new OperationContext(DEFAULT_ACCOUNT_ID); static final OperationContext context = TestUtil.DEFAULT_CONTEXT; static void enableAuth(String apiKey) { TestUtil.apiKey = apiKey; } static void disableAuth() { TestUtil.apiKey = null; } /** * Creates a string containing a number * * @param i The number to use * @return a message as a byte a array */ static byte[] createMessage(int i) { return ("This is message " + i + ".").getBytes(); } /** * Creates a flume event that has * <ul> * <li>a header named "messageNumber" with the string value of a number i</li> * <li>a header named "HEADER_DESTINATION_STREAM" with the name of a * destination</li> * <li>a body with the text "This is message number i.</li> * </ul> * * @param i The number to use * @param dest The destination name to use * @return a flume event */ static SimpleEvent createFlumeEvent(int i, String dest) { SimpleEvent event = new SimpleEvent(); Map<String, String> headers = new HashMap<String, String>(); headers.put("messageNumber", Integer.toString(i)); headers.put(Constants.HEADER_DESTINATION_STREAM, dest); if (TestUtil.apiKey != null) { headers.put(GatewayAuthenticator.CONTINUUITY_API_KEY, TestUtil.apiKey); LOG.warn("Set the API key on the flume event: " + apiKey); } event.setHeaders(headers); event.setBody(createMessage(i)); return event; } /** * Uses Flumes RPC client to send a number of flume events to a specified * port. * * @param port The port to use * @param dest The destination name to use as the destination * @param numMessages How many messages to send * @param batchSize Batch size to use for sending * @throws EventDeliveryException If sending fails for any reason */ static void sendFlumeEvents(int port, String dest, int numMessages, int batchSize) throws EventDeliveryException { RpcClient client = RpcClientFactory. getDefaultInstance("localhost", port, batchSize); try { List<org.apache.flume.Event> events = new ArrayList<org.apache.flume.Event>(); for (int i = 0; i < numMessages; ) { events.clear(); int bound = Math.min(i + batchSize, numMessages); for (; i < bound; i++) { events.add(createFlumeEvent(i, dest)); } client.appendBatch(events); } } catch (EventDeliveryException e) { client.close(); throw e; } client.close(); } /** * Uses Flume's RPC client to send a single event to a port * * @param port The port to use * @param event The event * @throws EventDeliveryException If something went wrong while sending */ static void sendFlumeEvent(int port, SimpleEvent event) throws EventDeliveryException { RpcClient client = RpcClientFactory. getDefaultInstance("localhost", port, 1); try { client.append(event); } catch (EventDeliveryException e) { client.close(); throw e; } client.close(); } /** * Creates an HTTP post that has * <ul> * <li>a header named "messageNumber" with the string value of a number i</li> * <li>a body with the text "This is message number i.</li> * </ul> * * @param i The number to use * @return a flume event */ static HttpPost createHttpPost(int port, String prefix, String path, String dest, int i) { String url = "http://localhost:" + port + prefix + path + dest; HttpPost post = new HttpPost(url); post.setHeader(dest + ".messageNumber", Integer.toString(i)); post.setEntity(new ByteArrayEntity(createMessage(i))); return post; } /** * Send an event to rest collector * * @param post The event as an Http post (see createHttpPost) * @throws IOException if sending fails */ static void sendRestEvent(HttpPost post) throws IOException { HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { LOG.error("Error sending event: " + response.getStatusLine()); } client.getConnectionManager().shutdown(); } /** * Creates an HTTP post for an event and sends it to the rest collector * * @param port The port as configured for the collector * @param prefix The path prefix as configured for the collector * @param path The path as configured for the collector * @param dest The destination name to use as the destination * @throws IOException if sending fails */ static void sendRestEvents(int port, String prefix, String path, String dest, int eventsToSend) throws IOException { for (int i = 0; i < eventsToSend; i++) { TestUtil.sendRestEvent(createHttpPost(port, prefix, path, dest, i)); } } static void verifyEvent(StreamEvent event, String collectorName, String destination, Integer expectedNo) { Assert.assertNotNull(event.getHeaders().get("messageNumber")); int messageNumber = Integer.valueOf(event.getHeaders().get("messageNumber")); if (expectedNo != null) Assert.assertEquals(messageNumber, expectedNo.intValue()); if (collectorName != null) Assert.assertEquals(collectorName, event.getHeaders().get(Constants.HEADER_FROM_COLLECTOR)); if (destination != null) Assert.assertEquals(destination, event.getHeaders().get(Constants.HEADER_DESTINATION_STREAM)); Assert.assertArrayEquals(createMessage(messageNumber), Bytes.toBytes(event.getBody())); } /** * A consumer that does nothing */ static class NoopConsumer extends Consumer { @Override public void single(StreamEvent event, String accountId) { } } /** * A consumer that verifies events, optionally for a fixed message number. * See verifyEvent for moire details. */ static class VerifyConsumer extends Consumer { Integer expectedNumber = null; String collectorName = null, destination = null; VerifyConsumer(String name, String dest) { this.collectorName = name; this.destination = dest; } VerifyConsumer(int expected, String name, String dest) { this.expectedNumber = expected; this.collectorName = name; this.destination = dest; } @Override protected void single(StreamEvent event, String accountId) throws Exception { TestUtil.verifyEvent(event, this.collectorName, this.destination, this.expectedNumber); } } static void consumeQueueAsEvents(OperationExecutor executor, String destination, String collectorName, int eventsExpected) throws Exception { // address the correct queue byte[] queueURI = QueueName.fromStream(new Id.Account(DEFAULT_ACCOUNT_ID), destination) .toString().getBytes(); // one deserializer to reuse StreamEventCodec deserializer = new StreamEventCodec(); // prepare the queue consumer QueueConfig config = new QueueConfig(QueuePartitioner.PartitionerType.FIFO, true); QueueConsumer consumer = new QueueConsumer(0, 0, 1, config); executor.execute(context, new QueueConfigure(queueURI, consumer)); QueueDequeue dequeue = new QueueDequeue(queueURI, consumer, config); for (int remaining = eventsExpected; remaining > 0; --remaining) { // dequeue one event and remember its ack pointer DequeueResult result = executor.execute(context, dequeue); Assert.assertTrue(result.isSuccess()); QueueEntryPointer ackPointer = result.getEntryPointer(); // deserialize and verify the event StreamEvent event = deserializer.decodePayload(result.getEntry().getData()); TestUtil.verifyEvent(event, collectorName, destination, null); // message number should be in the header "messageNumber" LOG.info("Popped one event, message number: " + event.getHeaders().get("messageNumber")); // ack the event so that it disappers from the queue QueueAck ack = new QueueAck(queueURI, ackPointer, consumer); List<WriteOperation> operations = new ArrayList<WriteOperation>(1); operations.add(ack); executor.commit(context, operations); } } /** * Verify that a given value can be retrieved for a given key via http GET * request * * @param executor the operation executor to use for access to data fabric * @param table the name of the table to test on * @param baseUri The URI for get request, without the key * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void writeAndGet(OperationExecutor executor, String baseUri, String table, byte[] key, byte[] value) throws Exception { // add the key/value to the data fabric Write write = new Write(table, key, Operation.KV_COL, value); List<WriteOperation> operations = new ArrayList<WriteOperation>(1); operations.add(write); executor.commit(context, operations); // make a get URL String getUrl = baseUri + (table == null ? "default" : table) + "/" + URLEncoder.encode(new String(key, "ISO8859_1"), "ISO8859_1"); LOG.info("GET request URI for key '" + new String(key) + "' is " + getUrl); // and issue a GET request to the server HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(getUrl); if (TestUtil.apiKey != null) { get.setHeader(GatewayAuthenticator.CONTINUUITY_API_KEY, TestUtil.apiKey); } HttpResponse response = client.execute(get); client.getConnectionManager().shutdown(); // verify the response is ok, throw exception if 403 if (HttpStatus.SC_FORBIDDEN == response.getStatusLine().getStatusCode()) throw new SecurityException("Authentication failed, access denied"); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // verify the length of the return value is the same as the original value's int length = (int) response.getEntity().getContentLength(); Assert.assertEquals(value.length, length); // verify that the value is actually the same InputStream content = response.getEntity().getContent(); if (length > 0) { byte[] bytes = new byte[length]; int bytesRead = content.read(bytes); Assert.assertEquals(length, bytesRead); Assert.assertArrayEquals(value, bytes); } // verify that the entire content was read Assert.assertEquals(-1, content.read(new byte[1])); } /** * Verify that a given value can be retrieved for a given key via http GET * request. This converts the key and value from String to bytes and calls * the byte-based method writeAndGet. * * @param executor the operation executor to use for access to data fabric * @param table the name of the table to test on * @param baseUri The URI for get request, without the key * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void writeAndGet(OperationExecutor executor, String baseUri, String table, String key, String value) throws Exception { writeAndGet(executor, baseUri, table, key.getBytes("ISO8859_1"), value.getBytes("ISO8859_1")); } /** * Verify that a given value can be retrieved for a given key via http GET * request. This converts the key and value from String to bytes and calls * the byte-based method writeAndGet. Uses default table * * @param executor the operation executor to use for access to data fabric * @param baseUri The URI for get request, without the key * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void writeAndGet(OperationExecutor executor, String baseUri, String key, String value) throws Exception { writeAndGet(executor, baseUri, null, key, value); } /** * Verify that a given value can be stored for a given key via http PUT * request * * @param executor the operation executor to use for access to data fabric * @param baseUri The URI for PUT request, without the key * @param table the name of the table to test on * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void putAndRead(OperationExecutor executor, String baseUri, String table, byte[] key, byte[] value) throws Exception { // make a get URL String putUrl = baseUri + (table == null ? "default" : table) + "/" + URLEncoder.encode(new String(key, "ISO8859_1"), "ISO8859_1"); LOG.info("PUT request URI for key '" + new String(key, "ISO8859_1") + "' is " + putUrl); // and issue a PUT request to the server HttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(putUrl); if (TestUtil.apiKey != null) { put.setHeader(GatewayAuthenticator.CONTINUUITY_API_KEY, TestUtil.apiKey); } put.setEntity(new ByteArrayEntity(value)); HttpResponse response = client.execute(put); client.getConnectionManager().shutdown(); // verify the response is ok, throw exception if 403 if (HttpStatus.SC_FORBIDDEN == response.getStatusLine().getStatusCode()) throw new SecurityException("Authentication failed, access denied"); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // read the key/value back from the data fabric Read read = new Read(key, Operation.KV_COL); OperationResult<Map<byte[],byte[]>> result = executor.execute(context, read); // verify the read value is the same as the original value Assert.assertFalse(result.isEmpty()); Assert.assertArrayEquals(value, result.getValue().get(Operation.KV_COL)); } /** * Verify that a given value can be stored for a given key via http PUT * request. This converts the key and value from String to bytes and calls * the byte-based method putAndRead. * * @param executor the operation executor to use for access to data fabric * @param baseUri The URI for REST request, without the key * @param table the name of the table to test on * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void putAndRead(OperationExecutor executor, String baseUri, String table, String key, String value) throws Exception { putAndRead(executor, baseUri, table, key.getBytes("ISO8859_1"), value.getBytes("ISO8859_1")); } /** * Verify that a given value can be stored for a given key via http PUT * request. This converts the key and value from String to bytes and calls * the byte-based method putAndRead. * * @param executor the operation executor to use for access to data fabric * @param baseUri The URI for REST request, without the key * @param key The key * @param value The value * @throws Exception if an exception occurs */ static void putAndRead(OperationExecutor executor, String baseUri, String key, String value) throws Exception { putAndRead(executor, baseUri, null, key, value); } /** * Send a GET request to the given URL and return the HTTP status * * @param url the URL to get */ public static int sendGetRequest(String url) throws Exception { HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(new HttpGet(url)); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } /** * Send a GET request to the given URL and return the HTTP status * * @param baseUrl the baseURL * @param table the name of the table to test on * @param key the key to delete */ public static int sendGetRequest(String baseUrl, String table, String key) throws Exception { String urlKey = URLEncoder.encode(key, "ISO8859_1"); String url = baseUrl + (table == null ? "default" : table) + "/" + urlKey; return sendGetRequest(url); } /** * Send a GET request to the given URL and return the HTTP status. Use * default table. * * @param baseUrl the baseURL * @param key the key to delete */ public static int sendGetRequest(String baseUrl, String key) throws Exception { return sendGetRequest(baseUrl, null, key); } /** * Send a DELETE request to the given URL and return the HTTP status * * @param url the URL to delete */ public static int sendDeleteRequest(String url) throws Exception { HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(new HttpDelete(url)); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } /** * Send a DELETE request to the given URL for the given key and return the * HTTP status * * @param baseUrl the baseURL * @param table the name of the table to test on * @param key the key to delete */ public static int sendDeleteRequest(String baseUrl, String table, String key) throws Exception { String urlKey = URLEncoder.encode(key, "ISO8859_1"); String url = baseUrl + (table == null ? "default" : table) + "/" + urlKey; return sendDeleteRequest(url); } /** * Send a DELETE request to the given URL for the given key and return the * HTTP status. Uses default table * * @param baseUrl the baseURL * @param key the key to delete */ public static int sendDeleteRequest(String baseUrl, String key) throws Exception { return sendDeleteRequest(baseUrl, null, key); } /** * Send a GET request to the given URL and return the Http response * * @param url the URL to get * @param headers map with header data */ public static HttpResponse sendGetRequest(String url, Map<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); if (headers!=null) { for(Map.Entry<String,String> header: headers.entrySet()) { get.setHeader(header.getKey(), header.getValue()); } } HttpResponse response = client.execute(new HttpGet(url)); client.getConnectionManager().shutdown(); return response; } /** * Send a POST request to the given URL and return the HTTP status * * @param url the URL to post to */ public static int sendPostRequest(String url) throws Exception { return sendPostRequest(url, new HashMap<String, String>()); } /** * Send a POST request to the given URL and return the HTTP status * * @param url the URL to post to * @param headers map with header data */ public static int sendPostRequest(String url, Map<String, String> headers) throws Exception { return sendPostRequest(url, new byte[0], headers); } /** * Send a Post request to the given URL and return the HTTP status * * @param url the URL to post to * @param content binary content * @param headers map with header data */ public static int sendPostRequest(String url, byte[] content, Map<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); if (headers!=null) { for(Map.Entry<String,String> header: headers.entrySet()) { post.setHeader(header.getKey(), header.getValue()); } } post.setEntity(new ByteArrayEntity(content)); HttpResponse response = client.execute(post); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } /** * Send a Post request to the given URL and return the HTTP status * * @param url the URL to post to * @param content String content * @param headers map with header data */ public static int sendPostRequest(String url, String content, Map<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); if (headers!=null) { for(Map.Entry<String,String> header: headers.entrySet()) { post.setHeader(header.getKey(), header.getValue()); } } post.setEntity(new StringEntity(content, "UTF-8")); HttpResponse response = client.execute(post); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } /** * Send a PUT request to the given URL and return the HTTP status * * @param url the URL to put to */ public static int sendPutRequest(String url) throws Exception { return sendPutRequest(url, new HashMap<String, String>()); } /** * Send a PUT request to the given URL and return the HTTP status * * @param url the URL to put to * @param headers map with header data */ public static int sendPutRequest(String url, Map<String, String> headers) throws Exception { return sendPutRequest(url, new byte[0], headers); } /** * Send a PUT request to the given URL and return the HTTP status * * @param url the URL to put to * @param content binary content * @param headers map with header data */ public static int sendPutRequest(String url, byte[] content, Map<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(url); if (headers!=null) { for(Map.Entry<String,String> header: headers.entrySet()) { put.setHeader(header.getKey(), header.getValue()); } } put.setEntity(new ByteArrayEntity(content)); HttpResponse response = client.execute(put); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } /** * Send a PUT request to the given URL and return the HTTP status * * @param url the URL to put to * @param content String content * @param headers map with header data */ public static int sendPutRequest(String url, String content, Map<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(url); if (headers!=null) { for(Map.Entry<String,String> header: headers.entrySet()) { put.setHeader(header.getKey(), header.getValue()); } } put.setEntity(new StringEntity(content, "UTF-8")); HttpResponse response = client.execute(put); client.getConnectionManager().shutdown(); return response.getStatusLine().getStatusCode(); } }
package com.mfk.web.maker.client; import java.util.Vector; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.search.client.DrawMode; import com.google.gwt.search.client.ExpandMode; import com.google.gwt.search.client.ImageResult; import com.google.gwt.search.client.ImageSearch; import com.google.gwt.search.client.KeepHandler; import com.google.gwt.search.client.LinkTarget; import com.google.gwt.search.client.Result; import com.google.gwt.search.client.ResultSetSize; import com.google.gwt.search.client.SafeSearchValue; import com.google.gwt.search.client.SearchControl; import com.google.gwt.search.client.SearchControlOptions; import com.google.gwt.search.client.SearchResultsHandler; import com.google.gwt.search.client.SearchStartingHandler; import com.google.gwt.search.client.WebSearch; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; // TODO(mjkelly): See this example: // https://code.google.com/apis/ajax/playground/#raw_search /** * Entry point classes define <code>onModuleLoad()</code>. */ public class MfkMaker implements EntryPoint { /** * This is the entry point method. */ public static Image selected; // arrays holding the attributes of the 3 items in the new triple public static TextBox names[] = {new TextBox(), new TextBox(), new TextBox()}; public static Image images[] = {null, null, null}; public static Button setButtons[] = {new Button("Set Item 1"), new Button("Set Item 2"), new Button("Set Item 3")}; public static MfkPanel items[] = {null, null, null}; // the actual image results public static Vector<Image> results = new Vector<Image>(); // the UI panel that displays the search results static Panel resultPanel; // a pane shown only when loading results static RootPanel resultsLoadingPanel = RootPanel.get("results-loading"); static ImageSearch imageSearch = new ImageSearch(); static public Button searchButton = new Button("Search"); static public TextBox searchBox = new TextBox(); static final EditDialog editDialog = new EditDialog(true); static final HorizontalPanel itemPanel = new HorizontalPanel(); static final String DEFAULT_SEARCH = "treehouse"; static final HTML LOADING = new HTML("<img src=\"/gwt/loading.gif\" alt=\"\"> Loading..."); public void onModuleLoad() { MfkMaker.resultsLoadingPanel.setVisible(false); MfkMaker.searchButton = new Button("Search"); MfkMaker.searchBox = new TextBox(); MfkMaker.resultPanel = new FlowPanel(); MfkMaker.imageSearch = new ImageSearch(); RootPanel.get("created-items").add(MfkMaker.itemPanel); MfkMaker.itemPanel.setSpacing(10); MfkMaker.names[0].setText("item one name"); MfkMaker.names[1].setText("item two name"); MfkMaker.names[2].setText("item three name"); for (int i = 1; i <= 3; i++) { Image img = new Image("/gwt/images/treehouse-" + i + ".jpeg"); MfkPanel item = new MfkPanel("Treehouse " + i, img); MfkMaker.addItem(item); } final SearchControlOptions options = new SearchControlOptions(); imageSearch.setSafeSearch(SafeSearchValue.STRICT); imageSearch.setResultSetSize(ResultSetSize.LARGE); options.add(imageSearch, ExpandMode.OPEN); options.setKeepLabel("<b>Keep It!</b>"); options.setLinkTarget(LinkTarget.BLANK); MfkMaker.editDialog.setAnimationEnabled(true); final ClickHandler resultClick = new ClickHandler() { public void onClick(ClickEvent event) { MfkMaker.editDialog.setImage((Image)event.getSource()); } }; // This handles the displayed result list. imageSearch.addSearchResultsHandler(new SearchResultsHandler() { public void onSearchResults(SearchResultsEvent event) { MfkMaker.resultsLoadingPanel.setVisible(false); JsArray<? extends Result> results = event.getResults(); System.out.println("List handler! #results = " + results.length()); for (int i = 0; i < results.length(); i++) { ImageResult r = (ImageResult)results.get(i); Image thumb = new Image(r.getThumbnailUrl()); thumb.setHeight(String.valueOf(r.getThumbnailHeight())); thumb.setWidth(String.valueOf(r.getThumbnailWidth())); thumb.addStyleName("search-result"); thumb.addClickHandler(resultClick); resultPanel.add(thumb); MfkMaker.results.add(thumb); } } }); // This handles the auto-set image. imageSearch.addSearchResultsHandler(new SearchResultsHandler() { public void onSearchResults(SearchResultsEvent event) { JsArray<? extends Result> results = event.getResults(); System.out.println("Top-result handler! #results = " + results.length()); if (results.length() >= 1) { ImageResult r = (ImageResult)results.get(0); Image image = new Image(r.getThumbnailUrl()); MfkMaker.editDialog.setImage(image); } } }); searchButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { MfkMaker.doSearch(); } }); searchBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == '\n' || event.getCharCode() == '\r') { MfkMaker.doSearch(); } } }); } public static void doSearch() { MfkMaker.resultsLoadingPanel.setVisible(true); MfkMaker.resultPanel.clear(); MfkMaker.results.clear(); MfkMaker.imageSearch.execute(MfkMaker.searchBox.getText()); } /** * Add an item to the page. * @param item the MfkPanel to add */ public static void addItem(MfkPanel item) { item.addToPanel(MfkMaker.itemPanel); } /** * Update the page's status with instructions, or how many items left to * create. */ public static void updateStatus() { if (MfkPanel.count > 0) { MfkMaker.setStatus((3 - MfkPanel.count) + " items remaining."); } else { MfkMaker.setStatus("Click an image to create an item."); } } /** * Set the page's status. * @param s status string */ private static void setStatus(String s) { Panel counter = RootPanel.get("counter"); counter.clear(); counter.add(new HTML("<h2>" + s + "</h2>")); } } class EditDialog extends DialogBox { private MfkPanel item = null; private Image editImage = new Image(); private TextBox editTitle = new TextBox(); private long lastSearchTimeMillis = 0; public EditDialog(boolean b) { super(b); } public void editItem(final MfkPanel item) { // TODO Auto-generated method stub this.item = item; System.out.println("Showing dialog for :" + item); this.editImage.setUrl(item.image.getUrl()); this.editTitle.setText(item.title); // TODO: We are *not* guaranteed to get the final state until the // search box loses focus! Fix this if deploying this UI! this.editTitle.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { maybeSetImageFromTitle(); } }); this.editTitle.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { maybeSetImageFromTitle(); } }); final Panel search = new VerticalPanel(); VerticalPanel p = new VerticalPanel(); p.setSpacing(5); // TODO: put this in CSS, come up with a well-reasoned value p.setWidth("600px"); Button create = new Button("<b>Save</b>"); create.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { System.out.println("Should create item here"); hide(); // update the existing item item.setTitle(editTitle.getText()); item.setImage(editImage); } }); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { hide(); } }); p.add(new HTML("<b>Name:</b>")); p.add(editTitle); p.add(new HTML("<b>Image:</b>")); p.add(editImage); p.add(new HTML("Not the image you wanted?")); HTML link = new HTML("See more images."); link.addClickHandler(new ClickHandler (){ public void onClick(ClickEvent event) { search.setVisible(!search.isVisible()); if (search.isVisible()) { MfkMaker.searchBox.setText(editTitle.getText()); MfkMaker.doSearch(); } } }); link.setStylePrimaryName("fakelink"); p.add(link); HorizontalPanel searchControls = new HorizontalPanel(); searchControls.add(MfkMaker.searchBox); searchControls.add(MfkMaker.searchButton); search.add(new HTML("<hr>Search for more images:")); search.add(searchControls); search.add(MfkMaker.resultPanel); search.setVisible(false); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.setSpacing(5); buttonPanel.add(create); buttonPanel.add(cancel); p.add(buttonPanel); p.add(search); this.setWidget(p); this.show(); this.center(); this.editTitle.setFocus(true); } /** * Check the time since the last time we auto-searched, perform a * search for the title string, and set the image to the top result. * * If don't perform the search if we just searched recently. */ public void maybeSetImageFromTitle() { long now = System.currentTimeMillis(); if (now - this.lastSearchTimeMillis > 1000) { this.lastSearchTimeMillis = now; MfkMaker.searchBox.setText(editTitle.getText()); MfkMaker.doSearch(); System.out.println("Auto-search: " + this.editTitle.getText() + ">"); } } /** * Set the image for the item under edit. */ public void setImage(Image image) { System.out.println("Set edit image url = " + image.getUrl()); this.editImage.setUrl(image.getUrl()); } public void hide() { super.hide(); this.item = null; } public MfkPanel getItem() { return this.item; } } class MfkPanel extends VerticalPanel { public String title; public Image image = new Image(); private Panel parent; // How many MfkPanels have been shown (i.e., added to another panel). static int count = 0; public MfkPanel(String title, Image image) { this.setTitle(title); this.setImage(image); System.out.println("MfkPanel: title:" + title + ", count:" + MfkPanel.count); } public void setImage(Image image) { this.image.setUrl(image.getUrl()); this.refresh(); } public void setTitle(String title) { this.title = title; this.refresh(); } /** * Add this object to another panel. This is a grab-bag of misc logic * associated with the MfkMaker. * @param p */ public void addToPanel(Panel p) { this.parent = p; MfkPanel.count++; this.parent.add(this); MfkMaker.updateStatus(); } /** * Remove this object from whatever panel it was added to. (It *must* have * been previously added.) */ public void remove() { this.parent.remove(this); MfkPanel.count MfkMaker.updateStatus(); } /** * Refresh the UI elements of the page. */ private void refresh() { this.clear(); final MfkPanel outerThis = this; Button editButton = new Button("Edit"); editButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { System.out.println("Delete " + this); MfkMaker.editDialog.editItem(outerThis); } }); this.add(editButton); this.add(new HTML("<i>" + this.title + "</i>")); this.add(this.image); } public String toString() { return "<MfkPanel: " + this.title + ", url=" + this.image.getUrl() + ">"; } } // TODO(mjkelly): Do client-side validation here. class SubmitHandler implements ClickHandler { public void onClick(ClickEvent event) { System.out.println("Want to create:\n" + "{n:" + MfkMaker.names[0].getText() + ", u:" + MfkMaker.images[0].getUrl() + "}\n" + "{n:" + MfkMaker.names[1].getText() + ", u:" + MfkMaker.images[1].getUrl() + "}\n" + "{n:" + MfkMaker.names[2].getText() + ", u:" + MfkMaker.images[2].getUrl() + "}"); String url = "/rpc/create/"; RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); StringBuffer reqData = new StringBuffer(); reqData.append("n1=").append(MfkMaker.names[0].getText()); reqData.append("&n2=").append(MfkMaker.names[1].getText()); reqData.append("&n3=").append(MfkMaker.names[2].getText()); reqData.append("&u1=").append(MfkMaker.images[0].getUrl()); reqData.append("&u2=").append(MfkMaker.images[1].getUrl()); reqData.append("&u3=").append(MfkMaker.images[2].getUrl()); try { builder.sendRequest(reqData.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { System.out.println("Error creating new Triple"); } public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 200) { System.out.println("Successful creation request: " + response.getText()); } else { System.out.println("Server didn't like our new triple. " + "Response code: " + response.getStatusCode() + ". Response text: " + response.getText()); } } }); } catch (RequestException e) { System.out.println("Error sending vote: " + e); } } }
package com.mfk.web.maker.client; import java.util.Vector; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.search.client.DrawMode; import com.google.gwt.search.client.ExpandMode; import com.google.gwt.search.client.ImageResult; import com.google.gwt.search.client.ImageSearch; import com.google.gwt.search.client.KeepHandler; import com.google.gwt.search.client.LinkTarget; import com.google.gwt.search.client.Result; import com.google.gwt.search.client.ResultSetSize; import com.google.gwt.search.client.SafeSearchValue; import com.google.gwt.search.client.SearchControl; import com.google.gwt.search.client.SearchControlOptions; import com.google.gwt.search.client.SearchResultsHandler; import com.google.gwt.search.client.SearchStartingHandler; import com.google.gwt.search.client.WebSearch; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.VerticalPanel; // TODO(mjkelly): See this example: // https://code.google.com/apis/ajax/playground/#raw_search /** * Entry point classes define <code>onModuleLoad()</code>. */ public class MfkMaker implements EntryPoint { /** * This is the entry point method. */ public static Vector<Image> results = new Vector<Image>(); public static Image selected; public static TextBox names[] = {new TextBox(), new TextBox(), new TextBox()}; public static Image images[] = {null, null, null}; public static Button setButtons[] = {new Button("Set Item 1"), new Button("Set Item 2"), new Button("Set Item 3")}; final static Button searchButton = new Button("Search"); final static TextBox searchBox = new TextBox(); final static RootPanel resultPanel = RootPanel.get("search-results"); final static ImageSearch imageSearch = new ImageSearch(); public void onModuleLoad() { MfkMaker.names[0].setText("item one name"); MfkMaker.names[1].setText("item two name"); MfkMaker.names[2].setText("item three name"); final SearchControlOptions options = new SearchControlOptions(); imageSearch.setSafeSearch(SafeSearchValue.STRICT); imageSearch.setResultSetSize(ResultSetSize.LARGE); options.add(imageSearch, ExpandMode.OPEN); options.setKeepLabel("<b>Keep It!</b>"); options.setLinkTarget(LinkTarget.BLANK); final ResultClickHandler resultClick = new ResultClickHandler(); imageSearch.addSearchResultsHandler(new SearchResultsHandler() { public void onSearchResults(SearchResultsEvent event) { JsArray<? extends Result> results = event.getResults(); System.out.println("Handler! #results = " + results.length()); for (int i = 0; i < results.length(); i++) { ImageResult r = (ImageResult)results.get(i); Image thumb = new Image(r.getThumbnailUrl()); thumb.setHeight(String.valueOf(r.getThumbnailHeight())); thumb.setWidth(String.valueOf(r.getThumbnailWidth())); thumb.addStyleName("search-result"); thumb.addClickHandler(resultClick); resultPanel.add(thumb); MfkMaker.results.add(thumb); } } }); imageSearch.execute("treehouse"); searchBox.setText("treehouse"); searchButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { resultPanel.clear(); MfkMaker.results.clear(); imageSearch.execute(searchBox.getText()); } }); searchBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == '\n' || event.getCharCode() == '\r') { resultPanel.clear(); MfkMaker.results.clear(); imageSearch.execute(searchBox.getText()); } } }); RootPanel.get("search-control").add(searchBox); RootPanel.get("search-control").add(searchButton); for (int i = 0; i < 3; i++) { MfkMaker.setButtons[i].setEnabled(false); MfkMaker.setButtons[i].addClickHandler(new SetImageHandler(i)); } RootPanel.get("saved-1-name").add(names[0]); RootPanel.get("saved-1-button").add(MfkMaker.setButtons[0]); RootPanel.get("saved-2-name").add(names[1]); RootPanel.get("saved-2-button").add(MfkMaker.setButtons[1]); RootPanel.get("saved-3-name").add(names[2]); RootPanel.get("saved-3-button").add(MfkMaker.setButtons[2]); final Button submitButton = new Button("Create!"); submitButton.addClickHandler(new SubmitHandler()); RootPanel.get("submit-button").add(submitButton); } } class ResultClickHandler implements ClickHandler { public void onClick(ClickEvent event) { for (Image img: MfkMaker.results) { img.setStylePrimaryName("search-result"); } Image source = (Image)event.getSource(); source.setStylePrimaryName("search-result-sel"); MfkMaker.selected = source; for (Button b: MfkMaker.setButtons) { b.setEnabled(true); } System.out.println("Clicked on " + source.getUrl()); } } class SetImageHandler implements ClickHandler { private int itemIndex; private String id; public SetImageHandler(int itemIndex) { this.itemIndex = itemIndex; this.id = "saved-" + Integer.toString(this.itemIndex+1) + "-inner"; } public void onClick(ClickEvent event) { System.out.println("Click #" + this.itemIndex + " -> " + this.id); RootPanel p = RootPanel.get(this.id); p.clear(); Image img = new Image(MfkMaker.selected.getUrl()); p.add(img); MfkMaker.images[this.itemIndex] = img; } } // TODO(mjkelly): Do client-side validation here. class SubmitHandler implements ClickHandler { public void onClick(ClickEvent event) { System.out.println("Want to create:\n" + "{n:" + MfkMaker.names[0].getText() + ", u:" + MfkMaker.images[0].getUrl() + "}\n" + "{n:" + MfkMaker.names[1].getText() + ", u:" + MfkMaker.images[1].getUrl() + "}\n" + "{n:" + MfkMaker.names[2].getText() + ", u:" + MfkMaker.images[2].getUrl() + "}"); String url = "/rpc/create/"; RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); StringBuffer reqData = new StringBuffer(); reqData.append("n1=").append(MfkMaker.names[0].getText()); reqData.append("&n2=").append(MfkMaker.names[1].getText()); reqData.append("&n3=").append(MfkMaker.names[2].getText()); reqData.append("&u1=").append(MfkMaker.images[0].getUrl()); reqData.append("&u2=").append(MfkMaker.images[1].getUrl()); reqData.append("&u3=").append(MfkMaker.images[2].getUrl()); try { builder.sendRequest(reqData.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { System.out.println("Error creating new Triple"); } public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 200) { System.out.println("Successful creation request: " + response.getText()); } else { System.out.println("Server didn't like our new triple. " + "Response code: " + response.getStatusCode() + ". Response text: " + response.getText()); } } }); } catch (RequestException e) { System.out.println("Error sending vote: " + e); } } }
package YOUR_PACKAGE_NAME; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import com.applovin.adview.AppLovinIncentivizedInterstitial; import com.applovin.sdk.AppLovinAd; import com.applovin.sdk.AppLovinAdClickListener; import com.applovin.sdk.AppLovinAdDisplayListener; import com.applovin.sdk.AppLovinAdLoadListener; import com.applovin.sdk.AppLovinAdRewardListener; import com.applovin.sdk.AppLovinAdVideoPlaybackListener; import com.applovin.sdk.AppLovinErrorCodes; import com.applovin.sdk.AppLovinSdk; import com.applovin.sdk.AppLovinSdkSettings; import com.mopub.common.LifecycleListener; import com.mopub.common.MoPubReward; import com.mopub.mobileads.CustomEventRewardedVideo; import com.mopub.mobileads.MoPubErrorCode; import com.mopub.mobileads.MoPubRewardedVideoManager; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import static android.util.Log.DEBUG; import static android.util.Log.ERROR; // PLEASE NOTE: We have renamed this class from "YOUR_PACKAGE_NAME.AppLovinRewardedAdapter" to "YOUR_PACKAGE_NAME.AppLovinCustomEventRewardedVideo", you can use either classname in your MoPub account. public class AppLovinCustomEventRewardedVideo extends CustomEventRewardedVideo implements AppLovinAdLoadListener, AppLovinAdDisplayListener, AppLovinAdClickListener, AppLovinAdVideoPlaybackListener, AppLovinAdRewardListener { private static final boolean LOGGING_ENABLED = true; private static final String DEFAULT_ZONE = ""; // A map of Zone -> `AppLovinIncentivizedInterstitial` to be shared by instances of the custom event. // This prevents skipping of ads as this adapter will be re-created and preloaded (along with underlying `AppLovinIncentivizedInterstitial`) // on every ad load regardless if ad was actually displayed or not. private static final Map<String, AppLovinIncentivizedInterstitial> GLOBAL_INCENTIVIZED_INTERSTITIAL_ADS = new HashMap<String, AppLovinIncentivizedInterstitial>(); private static boolean initialized; private AppLovinSdk sdk; private AppLovinIncentivizedInterstitial incentivizedInterstitial; private Activity parentActivity; private boolean fullyWatched; private MoPubReward reward; // MoPub Custom Event Methods @Override protected boolean checkAndInitializeSdk(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { log( DEBUG, "Initializing AppLovin rewarded video..." ); if ( !initialized ) { sdk = retrieveSdk( serverExtras, activity ); sdk.setPluginVersion( "MoPub-2.1.4" ); initialized = true; return true; } return false; } @Override protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { log( DEBUG, "Requesting AppLovin banner with serverExtras: " + serverExtras + " and localExtras: " + localExtras ); parentActivity = activity; // Zones support is available on AppLovin SDK 7.5.0 and higher final String zoneId; if ( AppLovinSdk.VERSION_CODE >= 750 && serverExtras != null && serverExtras.containsKey( "zone_id" ) ) { zoneId = serverExtras.get( "zone_id" ); } else { zoneId = DEFAULT_ZONE; } // Check if incentivized ad for zone already exists if ( GLOBAL_INCENTIVIZED_INTERSTITIAL_ADS.containsKey( zoneId ) ) { incentivizedInterstitial = GLOBAL_INCENTIVIZED_INTERSTITIAL_ADS.get( zoneId ); } else { // If this is a default Zone, create the incentivized ad normally if ( DEFAULT_ZONE.equals( zoneId ) ) { incentivizedInterstitial = AppLovinIncentivizedInterstitial.create( activity ); } // Otherwise, use the Zones API else { incentivizedInterstitial = createIncentivizedInterstitialForZoneId( zoneId, sdk ); } GLOBAL_INCENTIVIZED_INTERSTITIAL_ADS.put( zoneId, incentivizedInterstitial ); } incentivizedInterstitial.preload( this ); } @Override protected void showVideo() { if ( hasVideoAvailable() ) { fullyWatched = false; reward = null; incentivizedInterstitial.show( parentActivity, null, this, this, this, this ); } else { log( ERROR, "Failed to show an AppLovin rewarded video before one was loaded" ); MoPubRewardedVideoManager.onRewardedVideoPlaybackError( getClass(), "", MoPubErrorCode.VIDEO_PLAYBACK_ERROR ); } } @Override protected boolean hasVideoAvailable() { return incentivizedInterstitial.isAdReadyToDisplay(); } @Override @Nullable protected LifecycleListener getLifecycleListener() { return null; } @Override @NonNull protected String getAdNetworkId() { return ""; } @Override protected void onInvalidate() {} // Ad Load Listener @Override public void adReceived(final AppLovinAd ad) { log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() ); parentActivity.runOnUiThread( new Runnable() { @Override public void run() { MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( AppLovinCustomEventRewardedVideo.this.getClass(), "" ); } } ); } @Override public void failedToReceiveAd(final int errorCode) { log( DEBUG, "Rewarded video failed to load with error: " + errorCode ); parentActivity.runOnUiThread( new Runnable() { @Override public void run() { MoPubRewardedVideoManager.onRewardedVideoLoadFailure( AppLovinCustomEventRewardedVideo.this.getClass(), "", toMoPubErrorCode( errorCode ) ); } } ); } // Ad Display Listener @Override public void adDisplayed(final AppLovinAd ad) { log( DEBUG, "Rewarded video displayed" ); MoPubRewardedVideoManager.onRewardedVideoStarted( getClass(), "" ); } @Override public void adHidden(final AppLovinAd ad) { log( DEBUG, "Rewarded video dismissed" ); if ( fullyWatched && reward != null ) { log( DEBUG, "Rewarded" + reward.getAmount() + " " + reward.getLabel() ); MoPubRewardedVideoManager.onRewardedVideoCompleted( AppLovinCustomEventRewardedVideo.this.getClass(), "", reward ); } MoPubRewardedVideoManager.onRewardedVideoClosed( getClass(), "" ); } // Ad Click Listener @Override public void adClicked(final AppLovinAd ad) { log( DEBUG, "Rewarded video clicked" ); MoPubRewardedVideoManager.onRewardedVideoClicked( getClass(), "" ); } // Video Playback Listener @Override public void videoPlaybackBegan(final AppLovinAd ad) { log( DEBUG, "Rewarded video playback began" ); } @Override public void videoPlaybackEnded(final AppLovinAd ad, final double percentViewed, final boolean fullyWatched) { log( DEBUG, "Rewarded video playback ended at playback percent: " + percentViewed ); this.fullyWatched = fullyWatched; } // Reward Listener @Override public void userOverQuota(final AppLovinAd appLovinAd, final Map map) { log( ERROR, "Rewarded video validation request for ad did exceed quota with response: " + map ); } @Override public void validationRequestFailed(final AppLovinAd appLovinAd, final int errorCode) { log( ERROR, "Rewarded video validation request for ad failed with error code: " + errorCode ); } @Override public void userRewardRejected(final AppLovinAd appLovinAd, final Map map) { log( ERROR, "Rewarded video validation request was rejected with response: " + map ); } @Override public void userDeclinedToViewAd(final AppLovinAd appLovinAd) { log( DEBUG, "User declined to view rewarded video" ); MoPubRewardedVideoManager.onRewardedVideoClosed( getClass(), "" ); } @Override public void userRewardVerified(final AppLovinAd appLovinAd, final Map map) { final String currency = (String) map.get( "currency" ); final int amount = (int) Double.parseDouble( (String) map.get( "amount" ) ); // AppLovin returns amount as double log( DEBUG, "Verified " + amount + " " + currency ); reward = MoPubReward.success( currency, amount ); } // Dynamically create an instance of AppLovinIncentivizedInterstitial with a given zone without breaking backwards compatibility for publishers on older SDKs. private AppLovinIncentivizedInterstitial createIncentivizedInterstitialForZoneId(final String zoneId, final AppLovinSdk sdk) { AppLovinIncentivizedInterstitial incent = null; try { final Method method = AppLovinIncentivizedInterstitial.class.getMethod( "create", String.class, AppLovinSdk.class ); incent = (AppLovinIncentivizedInterstitial) method.invoke( null, zoneId, sdk ); } catch ( Throwable th ) { log( ERROR, "Unable to load ad for zone: " + zoneId + "..." ); MoPubRewardedVideoManager.onRewardedVideoLoadFailure( getClass(), "", MoPubErrorCode.ADAPTER_CONFIGURATION_ERROR ); } return incent; } // Utility Methods private static void log(final int priority, final String message) { if ( LOGGING_ENABLED ) { Log.println( priority, "AppLovinRewardedVideo", message ); } } private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) { return MoPubErrorCode.NETWORK_INVALID_STATE; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } } /** * Retrieves the appropriate instance of AppLovin's SDK from the SDK key given in the server parameters, or Android Manifest. */ static AppLovinSdk retrieveSdk(final Map<String, String> serverExtras, final Context context) { final String sdkKey = serverExtras != null ? serverExtras.get( "sdk_key" ) : null; final AppLovinSdk sdk; if ( !TextUtils.isEmpty( sdkKey ) ) { sdk = AppLovinSdk.getInstance( sdkKey, new AppLovinSdkSettings(), context ); } else { sdk = AppLovinSdk.getInstance( context ); } return sdk; } }
package io.gomint.server; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.StandardCopyOption; /** * This Bootstrap downloads all Libraries given inside of the "libs.dep" File in the Root * of the Application Workdir and then instanciates the Class which is given as Application * entry point. * * @author geNAZt * @version 1.0 */ public class Bootstrap { /** * Main entry point. May be used for custom dependency injection, dynamic * library class loaders and other experiments which need to be done before * the actual main entry point is executed. * * @param args The command-line arguments to be passed to the entryClass */ public static void main( String[] args ) { // Check if classloader has been changed (it should be a URLClassLoader) if ( !( ClassLoader.getSystemClassLoader() instanceof URLClassLoader ) ) { System.out.println( "System Classloader is no URLClassloader" ); System.exit( -1 ); } // Check if we need to create the libs Folder File libsFolder = new File( "libs/" ); if ( !libsFolder.exists() && !libsFolder.mkdirs() ) { System.out.println( "Could not create library Directory" ); System.exit( -1 ); } // Check the libs (versions and artifacts) checkLibs( libsFolder ); File[] files = libsFolder.listFiles(); if ( files == null ) { System.out.println( "Library Directory is corrupted" ); System.exit( -1 ); } // Scan the libs/ Directory for .jar Files for ( File file : files ) { if ( file.getAbsolutePath().endsWith( ".jar" ) ) { try { System.out.println( "Loading lib: " + file.getAbsolutePath() ); addJARToClasspath( file ); } catch ( IOException e ) { e.printStackTrace(); } } } // Load the Class entrypoint try { Class<?> coreClass = ClassLoader.getSystemClassLoader().loadClass( "io.gomint.server.GoMintServer" ); Constructor constructor = coreClass.getDeclaredConstructor( String[].class ); constructor.newInstance( new Object[]{ args } ); } catch ( ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e ) { e.printStackTrace(); } } /** * Download needed Libs from the central Maven repository or any other Repo (can be any url in the libs.dep file) * * @param libsFolder in which the downloads should be stored */ private static void checkLibs( File libsFolder ) { // Check if we are able to skip this if ( System.getProperty( "skip.libcheck", "false" ).equals( "true" ) ) { return; } // Load the dependency list try ( BufferedReader reader = new BufferedReader( new FileReader( new File( "libs.dep" ) ) ) ) { String libURL; while ( ( libURL = reader.readLine() ) != null ) { // Check for comment if ( libURL.isEmpty() || libURL.equals( System.getProperty("line.separator") ) || libURL.startsWith( " continue; } // Head first to get informations about the file URL url = new URL( libURL ); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod( "HEAD" ); // Filter out non java archive content types if ( !"application/java-archive".equals( urlConnection.getHeaderField( "Content-Type" ) ) ) { System.out.println( "Skipping the download of " + libURL + " because its not a Java Archive" ); continue; } // We need the contentLength to compare int contentLength = Integer.parseInt( urlConnection.getHeaderField( "Content-Length" ) ); String[] tempSplit = url.getPath().split( "/" ); String fileName = tempSplit[tempSplit.length - 1]; // Check if we have a file with the same length File libFile = new File( libsFolder, fileName ); if ( libFile.exists() && libFile.length() == contentLength ) { System.out.println( "Skipping the download of " + libURL + " because there already is a correct sized copy" ); continue; } // Download the file from the Server Files.copy( url.openStream(), libFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); System.out.println( "Downloading library: " + fileName ); } } catch ( IOException e ) { e.printStackTrace(); } } /** * Appends a JAR into the System Classloader * * @param moduleFile which should be added to the classpath * @throws IOException */ private static void addJARToClasspath( File moduleFile ) throws IOException { URL moduleURL = moduleFile.toURI().toURL(); Class[] parameters = new Class[]{ URL.class }; ClassLoader sysloader = ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { Method method = sysclass.getDeclaredMethod( "addURL", parameters ); method.setAccessible( true ); method.invoke( sysloader, new Object[]{ moduleURL } ); } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { e.printStackTrace(); throw new IOException( "Error, could not add URL to system classloader" ); } } }
package example.domain.web.nodriver; import org.apache.commons.lang.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.mock.web.MockHttpServletResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class HtmlPage { private String html; private Document dom; private Browser browser; public HtmlPage(MockHttpServletResponse response, Browser browser) throws Exception { this.browser = browser; if (StringUtils.startsWith(response.getContentType(), "text/html")) { html = response.getContentAsString(); dom = Jsoup.parse(html); } } public String currentURI() { return browser.currentURI(); } public void shouldHaveBodyClass(String index) { assertNotNull("Page is not text/html", html); assertThat(dom.body().classNames(), hasItem(index)); } public <T> T clickAndExpect(String selector, Class<T> pageClass) { Element link = expect(first(selector), "a"); String href = link.attr("href"); if (StringUtils.isEmpty(href)) { fail("Empty 'href' attribute in " + link.outerHtml()); return null; } return browser.get(href, pageClass); } public HtmlForm getForm(String selector) { Element form = expect(first(selector), "form"); return new HtmlForm(form, browser); } public Element first(String selector) { Elements elements = dom.select(selector); if (elements.isEmpty()) { fail("Cannot find " + selector + " in " + html); return null; } return elements.first(); } private Element expect(Element tag, String tagName) { assertThat("Unexpected element", tag.tagName(), equalTo(tagName)); return tag; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.card.server; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.server.OccupantOp; import com.threerings.parlor.card.Log; import com.threerings.parlor.card.data.Card; import com.threerings.parlor.card.data.CardCodes; import com.threerings.parlor.card.data.CardGameObject; import com.threerings.parlor.card.data.Deck; import com.threerings.parlor.card.data.Hand; import com.threerings.parlor.game.server.GameManager; import com.threerings.parlor.turn.server.TurnGameManager; import com.threerings.presents.client.InvocationService.ConfirmListener; import com.threerings.presents.data.ClientObject; import com.threerings.presents.dobj.MessageEvent; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.PresentsServer; /** * A manager class for card games. Handles common functions like dealing * hands of cards to all players. */ public class CardGameManager extends GameManager implements TurnGameManager, CardCodes { // Documentation inherited. protected void didStartup () { super.didStartup(); _cardgameobj = (CardGameObject)_gameobj; } // Documentation inherited. public void turnWillStart () {} // Documentation inherited. public void turnDidStart () {} // Documentation inherited. public void turnDidEnd () {} /** * Deals a hand of cards to the player at the specified index from * the given Deck. * * @param deck the deck from which to deal * @param size the size of the hand to deal * @param playerIndex the index of the target player * @return the hand dealt to the player, or null if the deal * was canceled because the deck did not contain enough cards */ public Hand dealHand (Deck deck, int size, int playerIndex) { if (deck.size() < size) { return null; } else { Hand hand = deck.dealHand(size); if (!isAI(playerIndex)) { CardGameSender.sendHand( (ClientObject)PresentsServer.omgr.getObject( _playerOids[playerIndex]), hand); } return hand; } } /** * Deals a hand of cards to each player from the specified * Deck. * * @param deck the deck from which to deal * @param size the size of the hands to deal * @return the array of hands dealt to each player, or null if * the deal was canceled because the deck did not contain enough * cards */ public Hand[] dealHands (Deck deck, int size) { if (deck.size() < size * _playerCount) { return null; } else { Hand[] hands = new Hand[_playerCount]; for (int i=0;i<_playerCount;i++) { hands[i] = dealHand(deck, size, i); } return hands; } } /** * Gets the player index of the specified client object, or -1 * if the client object does not represent a player. */ public int getPlayerIndex (ClientObject client) { int oid = client.getOid(); for (int i=0;i<_playerOids.length;i++) { if (_playerOids[i] == oid) { return i; } } return -1; } /** * Returns the client object corresponding to the specified player index. */ public ClientObject getClientObject (int pidx) { return (ClientObject)PresentsServer.omgr.getObject(_playerOids[pidx]); } /** * Sends a set of cards from one player to another. * * @param fromPlayerIdx the index of the player sending the cards * @param toPlayerIdx the index of the player receiving the cards * @param cards the cards to be exchanged */ public void transferCardsBetweenPlayers (final int fromPlayerIdx, final int toPlayerIdx, final Card[] cards) { // Notify the sender that the cards have been taken CardGameSender.sentCardsToPlayer(getClientObject(fromPlayerIdx), toPlayerIdx, cards); // Notify the receiver with the cards CardGameSender.sendCardsFromPlayer(getClientObject(toPlayerIdx), fromPlayerIdx, cards); // and everybody else in the room other than the sender and the // receiver with the number of cards sent final int senderOid = _playerOids[fromPlayerIdx], receiverOid = _playerOids[toPlayerIdx]; OccupantOp op = new OccupantOp() { public void apply (OccupantInfo info) { int oid = info.getBodyOid(); if (oid != senderOid && oid != receiverOid) { CardGameSender.cardsTransferredBetweenPlayers( (ClientObject)PresentsServer.omgr.getObject( oid), fromPlayerIdx, toPlayerIdx, cards.length); } } }; applyToOccupants(op); } /** The card game object. */ protected CardGameObject _cardgameobj; }
package org.jdesktop.swingx.plaf.basic; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.JXTitledPanel; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.plaf.PainterUIResource; import org.jdesktop.swingx.plaf.TitledPanelUI; /** * All TitledPanels contain a title section and a content section. The default * implementation for the title section relies on a Gradient background. All * title sections can have components embedded to the &quot;left&quot; or * &quot;right&quot; of the Title. * * @author Richard Bair * @author Jeanette Winzenburg * @author rah003 * */ public class BasicTitledPanelUI extends TitledPanelUI { private static final Logger LOG = Logger.getLogger(BasicTitledPanelUI.class.getName()); /** * JLabel used for the title in the Title section of the JTitledPanel. */ private JLabel caption; /** * The Title section panel. */ private JXPanel topPanel; /** * Listens to changes in the title of the JXTitledPanel component */ private PropertyChangeListener titleChangeListener; private JComponent left; private JComponent right; /** Creates a new instance of BasicTitledPanelUI */ public BasicTitledPanelUI() { } /** * Returns an instance of the UI delegate for the specified component. * Each subclass must provide its own static <code>createUI</code> * method that returns an instance of that UI delegate subclass. * If the UI delegate subclass is stateless, it may return an instance * that is shared by multiple components. If the UI delegate is * stateful, then it should return a new instance per component. * The default implementation of this method throws an error, as it * should never be invoked. */ public static ComponentUI createUI(JComponent c) { return new BasicTitledPanelUI(); } /** * Configures the specified component appropriate for the look and feel. * This method is invoked when the <code>ComponentUI</code> instance is being installed * as the UI delegate on the specified component. This method should * completely configure the component for the look and feel, * including the following: * <ol> * <li>Install any default property values for color, fonts, borders, * icons, opacity, etc. on the component. Whenever possible, * property values initialized by the client program should <i>not</i> * be overridden. * <li>Install a <code>LayoutManager</code> on the component if necessary. * <li>Create/add any required sub-components to the component. * <li>Create/install event listeners on the component. * <li>Create/install a <code>PropertyChangeListener</code> on the component in order * to detect and respond to component property changes appropriately. * <li>Install keyboard UI (mnemonics, traversal, etc.) on the component. * <li>Initialize any appropriate instance data. * </ol> * @param c the component where this UI delegate is being installed * * @see #uninstallUI * @see javax.swing.JComponent#setUI * @see javax.swing.JComponent#updateUI */ public void installUI(JComponent c) { assert c instanceof JXTitledPanel; JXTitledPanel titledPanel = (JXTitledPanel)c; installDefaults(titledPanel); caption = createAndConfigureCaption(titledPanel); topPanel = createAndConfigureTopPanel(titledPanel); installComponents(titledPanel); installListeners(titledPanel); } protected void installDefaults(JXTitledPanel titledPanel) { installProperty(titledPanel, "titlePainter", createBackgroundPainter()); installProperty(titledPanel, "titleForeground", UIManager.getColor("JXTitledPanel.title.foreground")); installProperty(titledPanel, "titleFont", UIManager.getFont("JXTitledPanel.title.font")); } protected void uninstallDefaults(JXTitledPanel titledPanel) { } protected Painter createBackgroundPainter() { Painter p = (Painter)UIManager.get("JXTitledPanel.title.painter"); return new PainterUIResource(p); } protected void installComponents(JXTitledPanel titledPanel) { topPanel.add(caption, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(4, 12, 4, 12), 0, 0)); if (titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION) instanceof JComponent) { setRightDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION)); } if (titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION) instanceof JComponent) { setLeftDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION)); } // swingx#500 if (!(titledPanel.getLayout() instanceof BorderLayout)){ titledPanel.setLayout(new BorderLayout()); } titledPanel.add(topPanel, BorderLayout.NORTH); titledPanel.setBorder(BorderFactory.createRaisedBevelBorder()); titledPanel.setOpaque(false); } protected void uninstallComponents(JXTitledPanel titledPanel) { titledPanel.remove(topPanel); } private JXPanel createAndConfigureTopPanel(JXTitledPanel titledPanel) { JXPanel topPanel = new JXPanel(); topPanel.setBackgroundPainter(titledPanel.getTitlePainter()); topPanel.setBorder(BorderFactory.createEmptyBorder()); topPanel.setLayout(new GridBagLayout()); return topPanel; } private JLabel createAndConfigureCaption(final JXTitledPanel titledPanel) { JLabel caption = new JLabel(titledPanel.getTitle()){ //#501 @Override public void updateUI(){ super.updateUI(); setForeground(titledPanel.getTitleForeground()); setFont(titledPanel.getTitleFont()); } }; caption.setFont(titledPanel.getTitleFont()); caption.setForeground(titledPanel.getTitleForeground()); return caption; } /** * Reverses configuration which was done on the specified component during * <code>installUI</code>. This method is invoked when this * <code>UIComponent</code> instance is being removed as the UI delegate * for the specified component. This method should undo the * configuration performed in <code>installUI</code>, being careful to * leave the <code>JComponent</code> instance in a clean state (no * extraneous listeners, look-and-feel-specific property objects, etc.). * This should include the following: * <ol> * <li>Remove any UI-set borders from the component. * <li>Remove any UI-set layout managers on the component. * <li>Remove any UI-added sub-components from the component. * <li>Remove any UI-added event/property listeners from the component. * <li>Remove any UI-installed keyboard UI from the component. * <li>Nullify any allocated instance data objects to allow for GC. * </ol> * @param c the component from which this UI delegate is being removed; * this argument is often ignored, * but might be used if the UI object is stateless * and shared by multiple components * * @see #installUI * @see javax.swing.JComponent#updateUI */ public void uninstallUI(JComponent c) { assert c instanceof JXTitledPanel; JXTitledPanel titledPanel = (JXTitledPanel) c; uninstallListeners(titledPanel); // JW: this is needed to make the gradient paint work correctly... // LF changes will remove the left/right components... topPanel.removeAll(); titledPanel.remove(topPanel); titledPanel.putClientProperty(JXTitledPanel.LEFT_DECORATION, left); titledPanel.putClientProperty(JXTitledPanel.RIGHT_DECORATION, right); caption = null; topPanel = null; titledPanel = null; left = null; right = null; } protected void installListeners(final JXTitledPanel titledPanel) { titleChangeListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("title")) { caption.setText((String)evt.getNewValue()); } else if (evt.getPropertyName().equals("titleForeground")) { caption.setForeground((Color)evt.getNewValue()); } else if (evt.getPropertyName().equals("titleFont")) { caption.setFont((Font)evt.getNewValue()); } else if ("titlePainter".equals(evt.getPropertyName())) { topPanel.setBackgroundPainter(titledPanel.getTitlePainter()); topPanel.repaint(); } } }; titledPanel.addPropertyChangeListener(titleChangeListener); } protected void uninstallListeners(JXTitledPanel titledPanel) { titledPanel.removePropertyChangeListener(titleChangeListener); } protected void installProperty(JComponent c, String propName, Object value) { try { BeanInfo bi = Introspector.getBeanInfo(c.getClass()); for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getName().equals(propName)) { Method m = pd.getReadMethod(); Object oldVal = m.invoke(c); if (oldVal == null || oldVal instanceof UIResource) { m = pd.getWriteMethod(); m.invoke(c, value); } } } } catch (Exception e) { LOG.log(Level.FINE, "Failed to install property " + propName, e); } } /** * Paints the specified component appropriate for the look and feel. * This method is invoked from the <code>ComponentUI.update</code> method when * the specified component is being painted. Subclasses should override * this method and use the specified <code>Graphics</code> object to * render the content of the component. * * @param g the <code>Graphics</code> context in which to paint * @param c the component being painted; * this argument is often ignored, * but might be used if the UI object is stateless * and shared by multiple components * * @see #update */ public void paint(Graphics g, JComponent c) { super.paint(g, c); } /** * Adds the given JComponent as a decoration on the right of the title * @param decoration */ public void setRightDecoration(JComponent decoration) { if (right != null) topPanel.remove(right); right = decoration; if (right != null) { topPanel.add(decoration, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0)); } } public JComponent getRightDecoration() { return right; } /** * Adds the given JComponent as a decoration on the left of the title * @param decoration */ public void setLeftDecoration(JComponent decoration) { if (left != null) topPanel.remove(left); left = decoration; if (left != null) { topPanel.add(left, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0)); } } public JComponent getLeftDecoration() { return left; } /** * @return the Container acting as the title bar for this component */ public Container getTitleBar() { return topPanel; } }
package org.jdesktop.swingx.plaf.macosx; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.border.Border; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import org.jdesktop.swingx.JXStatusBar; import org.jdesktop.swingx.plaf.StatusBarUI; /** * * @author rbair */ public class MacOSXStatusBarUI extends StatusBarUI { /** * The one and only JXStatusBar for this UI delegate */ private JXStatusBar statusBar; /** Creates a new instance of BasicStatusBarUI */ public MacOSXStatusBarUI() { } /** * Returns an instance of the UI delegate for the specified component. * Each subclass must provide its own static <code>createUI</code> * method that returns an instance of that UI delegate subclass. * If the UI delegate subclass is stateless, it may return an instance * that is shared by multiple components. If the UI delegate is * stateful, then it should return a new instance per component. * The default implementation of this method throws an error, as it * should never be invoked. */ public static ComponentUI createUI(JComponent c) { return new MacOSXStatusBarUI(); } /** * Configures the specified component appropriate for the look and feel. * This method is invoked when the <code>ComponentUI</code> instance is being installed * as the UI delegate on the specified component. This method should * completely configure the component for the look and feel, * including the following: * <ol> * <li>Install any default property values for color, fonts, borders, * icons, opacity, etc. on the component. Whenever possible, * property values initialized by the client program should <i>not</i> * be overridden. * <li>Install a <code>LayoutManager</code> on the component if necessary. * <li>Create/add any required sub-components to the component. * <li>Create/install event listeners on the component. * <li>Create/install a <code>PropertyChangeListener</code> on the component in order * to detect and respond to component property changes appropriately. * <li>Install keyboard UI (mnemonics, traversal, etc.) on the component. * <li>Initialize any appropriate instance data. * </ol> * @param c the component where this UI delegate is being installed * * @see #uninstallUI * @see javax.swing.JComponent#setUI * @see javax.swing.JComponent#updateUI */ @Override public void installUI(JComponent c) { assert c instanceof JXStatusBar; statusBar = (JXStatusBar)c; Border b = statusBar.getBorder(); if (b == null || b instanceof UIResource) { statusBar.setBorder(new BorderUIResource(BorderFactory.createEmptyBorder(4, 5, 4, 22))); } installDefaults(); } protected void installDefaults() { statusBar.setOpaque(false); } /** * Reverses configuration which was done on the specified component during * <code>installUI</code>. This method is invoked when this * <code>UIComponent</code> instance is being removed as the UI delegate * for the specified component. This method should undo the * configuration performed in <code>installUI</code>, being careful to * leave the <code>JComponent</code> instance in a clean state (no * extraneous listeners, look-and-feel-specific property objects, etc.). * This should include the following: * <ol> * <li>Remove any UI-set borders from the component. * <li>Remove any UI-set layout managers on the component. * <li>Remove any UI-added sub-components from the component. * <li>Remove any UI-added event/property listeners from the component. * <li>Remove any UI-installed keyboard UI from the component. * <li>Nullify any allocated instance data objects to allow for GC. * </ol> * @param c the component from which this UI delegate is being removed; * this argument is often ignored, * but might be used if the UI object is stateless * and shared by multiple components * * @see #installUI * @see javax.swing.JComponent#updateUI */ @Override public void uninstallUI(JComponent c) { assert c instanceof JXStatusBar; } }
package org.jivesoftware.wildfire.spi; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.jivesoftware.wildfire.*; import org.jivesoftware.wildfire.auth.UnauthorizedException; import org.jivesoftware.wildfire.component.InternalComponentManager; import org.jivesoftware.wildfire.container.BasicModule; import org.jivesoftware.wildfire.handler.PresenceUpdateHandler; import org.jivesoftware.wildfire.privacy.PrivacyList; import org.jivesoftware.wildfire.privacy.PrivacyListManager; import org.jivesoftware.wildfire.roster.Roster; import org.jivesoftware.wildfire.roster.RosterItem; import org.jivesoftware.wildfire.roster.RosterManager; import org.jivesoftware.wildfire.user.User; import org.jivesoftware.wildfire.user.UserManager; import org.jivesoftware.wildfire.user.UserNotFoundException; import org.xmpp.component.Component; import org.xmpp.packet.JID; import org.xmpp.packet.PacketError; import org.xmpp.packet.Presence; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Simple in memory implementation of the PresenceManager interface. * * @author Iain Shigeoka */ public class PresenceManagerImpl extends BasicModule implements PresenceManager { private static final String LAST_PRESENCE_PROP = "lastUnavailablePresence"; private static final String LAST_ACTIVITY_PROP = "lastActivity"; private SessionManager sessionManager; private UserManager userManager; private RosterManager rosterManager; private XMPPServer server; private PacketDeliverer deliverer; private PresenceUpdateHandler presenceUpdateHandler; private InternalComponentManager componentManager; public PresenceManagerImpl() { super("Presence manager"); // Use component manager for Presence Updates. componentManager = InternalComponentManager.getInstance(); } public boolean isAvailable(User user) { return sessionManager.getSessionCount(user.getUsername()) > 0; } public Presence getPresence(User user) { if (user == null) { return null; } Presence presence = null; for (ClientSession session : sessionManager.getSessions(user.getUsername())) { if (presence == null) { presence = session.getPresence(); } else { // Get the ordinals of the presences to compare. If no ordinal is available then // assume a value of -1 int o1 = presence.getShow() != null ? presence.getShow().ordinal() : -1; int o2 = session.getPresence().getShow() != null ? session.getPresence().getShow().ordinal() : -1; // Compare the presences' show ordinals if (o1 > o2) { presence = session.getPresence(); } } } return presence; } public Collection<Presence> getPresences(String username) { if (username == null) { return null; } List<Presence> presences = new ArrayList<Presence>(); for (ClientSession session : sessionManager.getSessions(username)) { presences.add(session.getPresence()); } return Collections.unmodifiableCollection(presences); } public String getLastPresenceStatus(User user) { String answer = null; String presenceXML = user.getProperties().get(LAST_PRESENCE_PROP); if (presenceXML != null) { try { // Parse the element Document element = DocumentHelper.parseText(presenceXML); answer = element.getRootElement().elementTextTrim("status"); } catch (DocumentException e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } return answer; } public long getLastActivity(User user) { long answer = -1; String offline = user.getProperties().get(LAST_ACTIVITY_PROP); if (offline != null) { try { answer = (System.currentTimeMillis() - Long.parseLong(offline)) / 1000; } catch (NumberFormatException e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } return answer; } public void userAvailable(Presence presence) { // Delete the last unavailable presence of this user since the user is now // available. Only perform this operation if this is an available presence sent to // THE SERVER and the presence belongs to a local user. if (presence.getTo() == null && server.isLocal(presence.getFrom())) { String username = presence.getFrom().getNode(); if (username == null || !userManager.isRegisteredUser(username)) { // Ignore anonymous users return; } try { User probeeUser = userManager.getUser(username); probeeUser.getProperties().remove(LAST_PRESENCE_PROP); } catch (UserNotFoundException e) { } } } public void userUnavailable(Presence presence) { // Only save the last presence status and keep track of the time when the user went // offline if this is an unavailable presence sent to THE SERVER and the presence belongs // to a local user. if (presence.getTo() == null && server.isLocal(presence.getFrom())) { String username = presence.getFrom().getNode(); if (username == null || !userManager.isRegisteredUser(username)) { // Ignore anonymous users return; } try { User probeeUser = userManager.getUser(username); if (!presence.getElement().elements().isEmpty()) { // Save the last unavailable presence of this user if the presence contains any // child element such as <status> probeeUser.getProperties().put(LAST_PRESENCE_PROP, presence.toXML()); } // Keep track of the time when the user went offline probeeUser.getProperties().put(LAST_ACTIVITY_PROP, String.valueOf(System.currentTimeMillis())); } catch (UserNotFoundException e) { } } } public void handleProbe(Presence packet) throws UnauthorizedException { String username = packet.getTo().getNode(); try { Roster roster = rosterManager.getRoster(username); RosterItem item = roster.getRosterItem(packet.getFrom()); if (item.getSubStatus() == RosterItem.SUB_FROM || item.getSubStatus() == RosterItem.SUB_BOTH) { probePresence(packet.getFrom(), packet.getTo()); } else { PacketError.Condition error = PacketError.Condition.not_authorized; if ((item.getSubStatus() == RosterItem.SUB_NONE && item.getRecvStatus() != RosterItem.RECV_SUBSCRIBE) || (item.getSubStatus() == RosterItem.SUB_TO && item.getRecvStatus() != RosterItem.RECV_SUBSCRIBE)) { error = PacketError.Condition.forbidden; } Presence presenceToSend = new Presence(); presenceToSend.setError(error); presenceToSend.setTo(packet.getFrom()); presenceToSend.setFrom(packet.getTo()); deliverer.deliver(presenceToSend); } } catch (UserNotFoundException e) { Presence presenceToSend = new Presence(); presenceToSend.setError(PacketError.Condition.forbidden); presenceToSend.setTo(packet.getFrom()); presenceToSend.setFrom(packet.getTo()); deliverer.deliver(presenceToSend); } } public boolean canProbePresence(JID prober, String probee) throws UserNotFoundException { RosterItem item = rosterManager.getRoster(probee).getRosterItem(prober); if (item.getSubStatus() == RosterItem.SUB_FROM || item.getSubStatus() == RosterItem.SUB_BOTH) { return true; } return false; } public void probePresence(JID prober, JID probee) { try { if (server.isLocal(probee)) { // Local probers should receive presences of probee in all connected resources Collection<JID> proberFullJIDs = new ArrayList<JID>(); if (prober.getResource() == null && server.isLocal(prober)) { for (ClientSession session : sessionManager.getSessions(prober.getNode())) { proberFullJIDs.add(session.getAddress()); } } else { proberFullJIDs.add(prober); } // If the probee is a local user then don't send a probe to the contact's server. // But instead just send the contact's presence to the prober Collection<ClientSession> sessions = sessionManager.getSessions(probee.getNode()); if (sessions.isEmpty()) { // If the probee is not online then try to retrieve his last unavailable // presence which may contain particular information and send it to the // prober String presenceXML = userManager.getUserProperty(probee.getNode(), LAST_PRESENCE_PROP); if (presenceXML != null) { try { // Parse the element Document element = DocumentHelper.parseText(presenceXML); // Create the presence from the parsed element Presence presencePacket = new Presence(element.getRootElement()); presencePacket.setFrom(probee.toBareJID()); // Check if default privacy list of the probee blocks the // outgoing presence PrivacyList list = PrivacyListManager.getInstance() .getDefaultPrivacyList(probee.getNode()); // Send presence to all prober's resources for (JID receipient : proberFullJIDs) { presencePacket.setTo(receipient); if (list == null || !list.shouldBlockPacket(presencePacket)) { // Send the presence to the prober deliverer.deliver(presencePacket); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } else { // The contact is online so send to the prober all the resources where the // probee is connected for (ClientSession session : sessions) { // Create presence to send from probee to prober Presence presencePacket = session.getPresence().createCopy(); presencePacket.setFrom(session.getAddress()); // Check if a privacy list of the probee blocks the outgoing presence PrivacyList list = session.getActiveList(); list = list == null ? session.getDefaultList() : list; // Send presence to all prober's resources for (JID receipient : proberFullJIDs) { presencePacket.setTo(receipient); if (list != null) { if (list.shouldBlockPacket(presencePacket)) { // Default list blocked outgoing presence so skip this session continue; } } try { deliverer.deliver(presencePacket); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } else { Component component = getComponent(probee); if (component != null) { // If the probee belongs to a component then ask the component to process the // probe presence Presence presence = new Presence(); presence.setType(Presence.Type.probe); presence.setFrom(prober); presence.setTo(probee); component.processPacket(presence); } else { // Check if the probee may be hosted by this server /*String serverDomain = server.getServerInfo().getName(); if (!probee.getDomain().contains(serverDomain)) {*/ if (server.isRemote(probee)) { // Send the probe presence to the remote server Presence probePresence = new Presence(); probePresence.setType(Presence.Type.probe); probePresence.setFrom(prober); probePresence.setTo(probee.toBareJID()); // Send the probe presence deliverer.deliver(probePresence); } else { // The probee may be related to a component that has not yet been connected so // we will keep a registry of this presence probe. The component will answer // this presence probe when he becomes online componentManager.addPresenceRequest(prober, probee); } } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } public void sendUnavailableFromSessions(JID recipientJID, JID userJID) { if (userManager.isRegisteredUser(userJID.getNode())) { for (ClientSession session : sessionManager.getSessions(userJID.getNode())) { // Do not send an unavailable presence if the user sent a direct available presence if (presenceUpdateHandler.hasDirectPresence(session, recipientJID)) { continue; } Presence presencePacket = new Presence(); presencePacket.setType(Presence.Type.unavailable); presencePacket.setFrom(session.getAddress()); // Ensure that unavailable presence is sent to all receipient's resources Collection<JID> recipientFullJIDs = new ArrayList<JID>(); if (server.isLocal(recipientJID)) { for (ClientSession targetSession : sessionManager .getSessions(recipientJID.getNode())) { recipientFullJIDs.add(targetSession.getAddress()); } } else { recipientFullJIDs.add(recipientJID); } for (JID jid : recipientFullJIDs) { presencePacket.setTo(jid); try { deliverer.deliver(presencePacket); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } // // Module management // public void initialize(XMPPServer server) { super.initialize(server); this.server = server; deliverer = server.getPacketDeliverer(); sessionManager = server.getSessionManager(); userManager = server.getUserManager(); presenceUpdateHandler = server.getPresenceUpdateHandler(); rosterManager = server.getRosterManager(); } private Component getComponent(JID probee) { // Check for registered components Component component = componentManager.getComponent(probee); if (component != null) { return component; } return null; } }
package verification.timed_state_exploration.zone; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Arrays; import java.util.HashSet; import java.util.List; import javax.swing.JOptionPane; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.stategraph.State; /** * This class is for storing and manipulating timing zones via difference bound matrices. * The underlying structure is backed by linked lists which yields the name * DBMLL (difference bound matrix linked list). A difference bound matrix has the form * t0 t1 t2 t3 * t0 m00 m01 m02 m03 * t1 m10 m11 m12 m13 * t2 m20 m21 m22 m23 * t3 m30 m31 m32 m33 * where tj - ti<= mij. In particular, m0k is an upper bound for tk and -mk is a lower * bound for tk. * * The timers are referred to by an index. * * This class also contains a public nested class DiagonalNonZeroException which extends * java.lang.RuntimeException. This exception may be thrown if the diagonal entries of a * zone become nonzero. * * @author Andrew N. Fisher * */ public class Zone extends ZoneType { // Abstraction Function : // The difference bound matrix is represented by int[][]. // In order to keep track of the upper and lower bounds of timers from when they are first // enabled, the matrix will be augmented by a row and a column. The first row will contain // the upper bounds and the first column will contain the negative of the lower bounds. // For one timer t1 that is between 2 and 3, we might have // lb t0 t1 // ub x 0 3 // t0 0 m m // t1 -2 m m // where x is not important (and will be given a zero value), 3 is the upper bound on t1 // and -2 is the negative of the lower bound. The m values represent the actual difference // bound matrix. Also note that the column heading are not part of the stored representation // lb stands for lower bound while ub stands for upper bound. // This upper and lower bound information is called the Delay for a Transition object. // Since a timer is tied directly to a Transition, the timers are index by the corresponding // Transition's index in a LPNTranslator. // The timers are named by an integer referred to as the index. The _indexToTimer array // connects the index in the DBM sub-matrix to the index of the timer. For example, // a the timer t1 // Representation invariant : // Zones are immutable. // Integer.MAX_VALUE is used to logically represent infinity. // The lb and ub values for a timer should be set when the timer is enabled. // A negative hash code indicates that the hash code has not been set. // The index of the timer in _indexToTimer is the index in the DBM and should contain // the zeroth timer. // The array _indexToTimer should always be sorted. /* The lower and upper bounds of the times as well as the dbm. */ private int[][] _matrix; /* Maps the index to the timer. The index is row/column of the DBM sub-matrix. * Logically the zero timer is given index -1. * */ private int[] _indexToTimer; /* The hash code. */ private int _hashCode; /* A lexicon between a transitions index and its name. */ private static HashMap<Integer, Transition> _indexToTransition; /* Set if a failure in the testSplit method has fired already. */ private static boolean _FAILURE = false; /* Hack to pass a parameter to the equals method though a variable */ private boolean subsetting = false; /** * Construct a zone that has the given timers. * @param timers * The ith index of the array is the index of the timer. For example, * if timers = [1, 3, 5], then the zeroth row/column of the DBM is the * timer of the transition with index 1, the first row/column of the * DBM is the timer of the transition with index 3, and the 2nd * row/column is the timer of the transition with index 5. Do not * include the zero timer. * @param matrix * The DBM augmented with the lower and upper bounds of the delays for the * transitions. For example, suppose a zone has timers [1, 3, 5] (as * described in the timers parameters). The delay for transition 1 is * [1, 3], the delay for transition 3 is [2,5], and the delay for * transition 5 is [4,6]. Also suppose the DBM is * t0 t1 t3 t5 * t0 | 0, 3, 3, 3 | * t1 | 0, 0, 0, 0 | * t3 | 0, 0, 0, 0 | * t5 | 0, 0, 0, 0 | * Then the matrix that should be passed is * lb t0 t1 t3 t5 * ub| 0, 0, 3, 5, 6| * t0| 0, 0, 3, 3, 3| * t1|-1, 0, 0, 0, 0| * t3|-2, 0, 0, 0, 0| * t5|-4, 0, 0, 0, 0| * The matrix should be non-null and the zero timer should always be the * first timer, even when there are no other timers. */ public Zone(int[] timers, int[][] matrix) { // A negative number indicates that the hash code has not been set. _hashCode = -1; // Make a copy to reorder the timers. _indexToTimer = Arrays.copyOf(timers, timers.length); // Sorting the array. Arrays.sort(_indexToTimer); //if(_indexToTimer[0] != 0) if(_indexToTimer[0] != -1) { // Add the zeroth timer. int[] newIndexToTimer = new int[_indexToTimer.length+1]; for(int i=0; i<_indexToTimer.length; i++) { newIndexToTimer[i+1] = _indexToTimer[i]; } _indexToTimer = newIndexToTimer; _indexToTimer[0] = -1; } // if(_indexToTimer[0] < 0) // // Add a zero timer. // else if(_indexToTimer[0] > 0) // int[] newTimerIndex = new int[_indexToTimer.length+1]; // for(int i=0; i<_indexToTimer.length; i++) // newTimerIndex[i+1] = _indexToTimer[i]; // Map the old index of the timer to the new index of the timer. HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>(); // For the old index, find the new index. for(int i=0; i<timers.length; i++) { // Since the zeroth timer is not included in the timers passed // to the index in the DBM is 1 more than the index of the timer // in the timers array. newIndex.put(i+1, Arrays.binarySearch(_indexToTimer, timers[i])); } // Add the zero timer index. newIndex.put(0, 0); // Initialize the matrix. _matrix = new int[matrixSize()][matrixSize()]; // Copy the DBM for(int i=0; i<dbmSize(); i++) { for(int j=0; j<dbmSize(); j++) { // Copy the passed in matrix to _matrix. setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]); // In the above, changed setDBMIndex to setdbm } } // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound // so the index starts at i=1, the first non-zero timer. for(int i=1; i< dbmSize(); i++) { setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]); // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound // and the matrix stores the negative of the lower bound. So the matrix value // must be multiplied by -1. setLowerBoundbydbmIndex(newIndex.get(i), -1*matrix[dbmIndexToMatrixIndex(i)][0]); } recononicalize(); } /** * Initializes a zone according to the markings of state. * @param currentState * The zone is initialized as if all enabled timers * have just been enabled. */ public Zone(State initialState) { LhpnFile lpn = initialState.getLpn(); Transition[] allTran = lpn.getAllTransitions(); /* Create the lexicon if it has not already been created. */ if(_indexToTransition == null) { _indexToTransition = new HashMap<Integer, Transition>(); // Get the transitions. allTran = lpn.getAllTransitions(); for(Transition T : allTran) { _indexToTransition.put(T.getIndex(), T); } } _hashCode = -1; //_indexToTimer = initialState.getTranVector(); boolean[] enabledTran = initialState.getTranVector(); // int count = 0; // // Find the size of the enabled transitions. // for(int i=0; i<enabledTran.length; i++) // if(enabledTran[i]) // count++; // _indexToTimer = new int[count]; // count =0; // // Initialize the _indexToTimer. // for(int i=0; i<enabledTran.length; i++) // if(enabledTran[i]) // _indexToTimer[count++] = i; // Associate the Transition with its index. //TreeMap<Integer, Transition> indexToTran = new TreeMap<Integer, Transition>(); //_indexToTransition = new HashMap<Integer, Transition>(); // Get out the Transitions to compare with the enableTran to determine which are // enabled. //Transition[] allTran = lpn.getAllTransitions(); HashMap<Integer, Transition> enabledTranMap = new HashMap<Integer, Transition>(); for(Transition T : allTran) { int index = T.getIndex(); if(enabledTran[index]) { //indexToTran.put(index, T); enabledTranMap.put(index, T); } } // Enabled timers plus the zero timer. //_indexToTimer = new int[indexToTran.size()+1]; //_indexToTimer = new int[_indexToTransition.size()+1]; _indexToTimer = new int[enabledTranMap.size()+1]; _indexToTimer[0] = -1; // Load the indices starting at index 1, since the zero timer will // be index 0. int count =1; // Load the indices of the Transitions into _indexToTimer. //for(int i : indexToTran.keySet()) //for(int i : _indexToTransition.keySet()) for(int i : enabledTranMap.keySet()) { _indexToTimer[count] = i; count++; } Arrays.sort(_indexToTimer); _matrix = new int[matrixSize()][matrixSize()]; for(int i=1; i<dbmSize(); i++) { // Get the name for the timer in the i-th column/row of DBM //String tranName = indexToTran.get(_indexToTimer[i]).getName(); String tranName = _indexToTransition.get(_indexToTimer[i]).getName(); ExprTree delay = lpn.getDelayTree(tranName); // Get the values of the variables for evaluating the ExprTree. HashMap<String, String> varValues = lpn.getAllVarsWithValuesAsString(initialState.getVector()); // Set the upper and lower bound. int upper, lower; if(delay.getOp().equals("uniform")) { ExprTree lowerDelay = delay.getLeftChild(); ExprTree upperDelay = delay.getRightChild(); lower = (int) lowerDelay.evaluateExpr(varValues); upper = (int) upperDelay.evaluateExpr(varValues); } else { lower = (int) delay.evaluateExpr(varValues); upper = lower; } setLowerBoundbydbmIndex(i, lower); setUpperBoundbydbmIndex(i, upper); } // Advance the time and tighten the bounds. advance(); recononicalize(); } /** * Zero argument constructor for use in methods that create Zones where the members * variables will be set by the method. */ private Zone() { _matrix = new int[0][0]; _indexToTimer = new int[0]; _hashCode = -1; } /** * Logically the DBM is the sub-matrix of _matrix obtained by removing the zeroth * row and column. This method retrieves the (i,j) element of the DBM. * @param i * The i-th row of the DBM. * @param j * The j-th column of the DBM. * @return * The (i,j) element of the DBM. */ // public int getDBMIndex(int i, int j) // return _matrix[i+1][j+1]; /** * Logically the DBM is the sub-matrix of _matrix obtained by removing the zeroth * row and column. This method sets the (i,j) element of the DBM. * @param i * The ith row of the DBM. * @param j * The jth column of the DBM. * @param value * The value of the matrix. */ // private void setDBMIndex(int i, int j, int value) // _matrix[i+1][j+1] = value; /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getUpperBoundbyTransitionIndex(int) */ public int getUpperBoundbyTransitionIndex(int timer) { return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimer, timer)); } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getUpperBoundbydbmIndex(int) */ public int getUpperBoundbydbmIndex(int index) { return _matrix[0][dbmIndexToMatrixIndex(index)]; } /** * Set the value of the upper bound for the delay. * @param timer * The timer's index. * @param value * The value of the upper bound. */ public void setUpperBoundbyTransitionIndex(int timer, int value) { setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimer, timer), value); } /** * Set the value of the upper bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @param value * The value of the upper bound. */ public void setUpperBoundbydbmIndex(int index, int value) { _matrix[0][dbmIndexToMatrixIndex(index)] = value; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getLowerBoundbyTransitionIndex(int) */ public int getLowerBoundbyTransitionIndex(int timer) { return -1*getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimer, timer)); } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getLowerBoundbydbmIndex(int) */ public int getLowerBoundbydbmIndex(int index) { return _matrix[dbmIndexToMatrixIndex(index)][0]; } /** * Set the value of the lower bound for the delay. * @param timer * The timer's index. * @param value * The value of the lower bound. */ public void setLowerBoundbyTransitionIndex(int timer, int value) { setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimer,timer), value); } /** * Set the value of the lower bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @param value * The value of the lower bound. */ public void setLowerBoundbydbmIndex(int index, int value) { _matrix[dbmIndexToMatrixIndex(index)][0] = -1*value; } /** * Converts the index of the DBM to the index of _matrix. * @param i * The row/column index of the DBM. * @return * The row/column index of _matrix. */ private int dbmIndexToMatrixIndex(int i) { return i+1; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getdbm(int, int) */ public int getDbmEntry(int i, int j) { return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]; } /** * Sets an entry of the DBM using the DBM's addressing. * @param i * The row of the DBM. * @param j * The column of the DBM. * @param value * The new value for the entry. */ private void setDbmEntry(int i, int j, int value) { _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value; } /** * Converts the index of the timer from the _indexToTimer array to the index of _matrix. * @param i * The index of the timer from the _indexToTimer array. * @return * The index in the _matrix. */ private int timerIndexToMatrixIndex(int i) { //return i+2; //return i+1; return dbmIndexToMatrixIndex(Arrays.binarySearch(_indexToTimer, i)); } /** * Returns the index of the the transition in the DBM given the index of the * transition. * @param i * The transition's index. * @return * The row/column of the DBM associated with the i-th transition. */ private int timerIndexToDBMIndex(int i) { return Arrays.binarySearch(_indexToTimer, i); } /** * Converts the index of _matrix to the index of the DBM. * @param i * The row/column index of _matrix. * @return * The row/column index of the DBM. */ private int matrixIndexTodbmIndex(int i) { return i-1; } /** * The matrix labeled with 'ti' where i is the transition index associated with the timer. */ public String toString() { String result = "Timer and delay.\n"; int count = 0; // Print the timers. for(int i=1; i<_indexToTimer.length; i++, count++) { if(_indexToTransition == null) { // If an index to transition map has not been set up, // use the transition index for the timer. result += " t" + _indexToTimer[i] + " : "; } else { result += " " + _indexToTransition.get(_indexToTimer[i]) + ":"; } result += "[ " + -1*getLowerBoundbydbmIndex(i) + ", " + getUpperBoundbydbmIndex(i) + " ]"; if(count > 9) { result += "\n"; count = 0; } } result += "\nDBM\n"; //result += "|"; // Print the DBM. for(int i=0; i<_indexToTimer.length; i++) { //result += " " + _matrix[i][0]; result += "| " + getDbmEntry(i, 0); //for(int j=1; j<_indexToTimer.length; j++) for(int j=1; j<_indexToTimer.length; j++) { //result += ", " + _matrix[i][j]; result += ", " + getDbmEntry(i, j); } result += " |\n"; } //result += "|"; return result; } /** * Tests for equality. Overrides inherited equals method. * @return True if o is equal to this object, false otherwise. */ public boolean equals(Object o) { // Check if the reference is null. if(o == null) { return false; } // Check that the type is correct. if(!(o instanceof Zone)) { return false; } // Check for equality using the Zone equality. return equals((Zone) o); } /** * Tests for equality. * @param * The Zone to compare. * @return * True if the zones are non-null and equal, false otherwise. */ public boolean equals(Zone otherZone) { // Check if the reference is null first. if(otherZone == null) { return false; } // Check for reference equality. if(this == otherZone) { return true; } // Check hash codes if not doing subsets. //if(!ZoneType.getSubsetFlag()){ //if(!subsetting){ // If the hash codes are different, then the objects are not equal. if(this.hashCode() != otherZone.hashCode()) { return false; } // Check if the timers are the same. // if(!Arrays.equals(this._indexToTimer, otherZone._indexToTimer)) // return false; if(this._indexToTimer.length != otherZone._indexToTimer.length){ return false; } for(int i=0; i<this._indexToTimer.length; i++){ if(this._indexToTimer[i] != otherZone._indexToTimer[i]){ return false; } } // Check if the matrix is the same if subsets are not being used. // Check if the entries of other are less than or equal to this if // subset are in use. for(int i=0; i<_matrix.length; i++) { for(int j=0; j<_matrix[0].length; j++) { // if(ZoneType.getSubsetFlag()){ // //if(subsetting){ // // Subsets are in use. // if(!(otherZone._matrix[i][j] <= this._matrix[i][j])){ // return false; // else{ // Subsets are not in use. if(!(this._matrix[i][j] == otherZone._matrix[i][j])) { return false; } } } return true; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#subset(Zone) */ public boolean subset(ZoneType otherZone){ // Check if the reference is null first. if(otherZone == null) { return false; } // Check for reference equality. if(this == otherZone) { return true; } Zone oZ; if( !(otherZone instanceof Zone)){ throw new UnsupportedOperationException("Tried subset with Zone and other" + "ZoneType"); } else{ oZ = (Zone) otherZone; } if(this._indexToTimer.length != oZ._indexToTimer.length){ return false; } for(int i=0; i<this._indexToTimer.length; i++){ if(this._indexToTimer[i] != oZ._indexToTimer[i]){ return false; } } // Check if the matrix is the same if subsets are not being used. // Check if the entries of other are less than or equal to this if // subset are in use. for(int i=0; i<_matrix.length; i++) { for(int j=0; j<_matrix[0].length; j++) { if(!(this._matrix[i][j] <= oZ._matrix[i][j])){ return false; } } } return true; } /** * Overrides the hashCode. */ public int hashCode() { // Check if the hash code has been set. if(_hashCode <0) { _hashCode = createHashCode(); } return _hashCode; } /** * Creates a hash code for a Zone object. * @return * The hash code. */ private int createHashCode() { int newHashCode = Arrays.hashCode(_indexToTimer); for(int i=0; i<_matrix.length; i++) { newHashCode ^= Arrays.hashCode(_matrix[i]); } return Math.abs(newHashCode); } /** * Checks if the array has square dimensions. * @param array * The array to test. * @return * True if the arrays is square, non-zero, and non-null, false otherwise. */ private boolean checkSquare(int[][] array) { //boolean result = true; if(array == null ) { return false; } if(array.length == 0) { return true; } int dimension = array.length; for(int i=0; i<array.length; i++) { if(array[i] == null || array[i].length != dimension) { return false; } } return false; } /** * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer. * @return * The size of the DBM. */ private int dbmSize() { return _indexToTimer.length; } /** * The size of the matrix. * @return * The size of the matrix. This is calculated using the size of _indexToTimer. */ private int matrixSize() { return _indexToTimer.length + 1; } /** * Performs the Floyd's least pairs algorithm to reduce the DBM. */ private void recononicalize() { // TODO : Check if finished. for(int k=0; k<dbmSize(); k++) { for (int i=0; i<dbmSize(); i++) { for(int j=0; j<dbmSize(); j++) { if(getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) { setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j)); } if( (i==j) && getDbmEntry(i, j) != 0) { throw new DiagonalNonZeroException("Entry (" + i + ", " + j + ")" + " became " + getDbmEntry(i, j) + "."); } } } } } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#exceedsLowerBoundbyTransitionIndex(int) */ public boolean exceedsLowerBoundbyTransitionIndex(int timer) { // TODO : Check if finished. return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimer, timer)); } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#exceedsLowerBoundbydbmIndex(int) */ public boolean exceedsLowerBoundbydbmIndex(int index) { // TODO: Check if finished. // Note : Make sure that the lower bound is stored as a negative number // and that the inequality is correct. return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)]; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State) */ public ZoneType fireTransitionbyTransitionIndex(int timer, int[] enabledTimers, State state) { // TODO: Check if finish. int index = Arrays.binarySearch(_indexToTimer, timer); //return fireTransitionbydbmIndex(Arrays.binarySearch(_indexToTimer, timer), //enabledTimers, state); // Check if the value is in this zone to fire. if(index < 0){ return this; } return fireTransitionbydbmIndex(index, enabledTimers, state); } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#fireTransitionbydbmIndex(int, int[], verification.platu.stategraph.State) */ public ZoneType fireTransitionbydbmIndex(int index, int[] enabledTimers, State state) { // TODO: Finish Zone newZone = new Zone(); // Copy over the enabledTimers adding a zero timer. //newZone._indexToTimer = enabledTimers; newZone._indexToTimer = new int[enabledTimers.length+1]; // Put the _indexToTimer value for the zeroth timer to -1. // See the Abstraction Function section at the top of the // class for a discussion on why. newZone._indexToTimer[0] = -1; for(int i=0; i<enabledTimers.length; i++) { newZone._indexToTimer[i+1]=enabledTimers[i]; } Arrays.sort(newZone._indexToTimer); HashSet<Integer> newTimers = new HashSet<Integer>(); HashSet<Integer> oldTimers = new HashSet<Integer>(); for(int i=0; i<newZone._indexToTimer.length; i++) { // Determine if each value is a new timer or old. if(Arrays.binarySearch(this._indexToTimer, newZone._indexToTimer[i]) >= 0 ) { // The timer was already present in the zone. oldTimers.add(newZone._indexToTimer[i]); } else { // The timer is a new timer. newTimers.add(newZone._indexToTimer[i]); } } // Create the new matrix. newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()]; // TODO: For simplicity, make a copy of the current zone and perform the // restriction and re-canonicalization. Later add a copy re-canonicalization // that does the steps together. Zone tempZone = this.clone(); tempZone.restrict(index); tempZone.recononicalize(); // Copy the tempZone to the new zone. for(int i=0; i<tempZone.dbmSize(); i++) { if(!oldTimers.contains(tempZone._indexToTimer[i])) { // break; continue; } // Get the new index of for the timer. int newIndexi = i==0 ? 0 : Arrays.binarySearch(newZone._indexToTimer, tempZone._indexToTimer[i]); for(int j=0; j<tempZone.dbmSize(); j++) { if(!oldTimers.contains(tempZone._indexToTimer[j])) { // break; continue; } int newIndexj = j==0 ? 0 : Arrays.binarySearch(newZone._indexToTimer, tempZone._indexToTimer[j]); newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)][newZone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j); // In above, changed getDBMIndex to getdbm } } // Copy the upper and lower bounds. //for(int i=0; i<tempZone.dbmSize(); i++) for(int i=1; i<tempZone.dbmSize(); i++) { if(!oldTimers.contains(tempZone._indexToTimer[i])) { // break; continue; } newZone.setLowerBoundbyTransitionIndex(tempZone._indexToTimer[i], -1*tempZone.getLowerBoundbydbmIndex(i)); // The minus sign is because _matrix stores the negative of the lower bound. newZone.setUpperBoundbyTransitionIndex(tempZone._indexToTimer[i], tempZone.getUpperBoundbydbmIndex(i)); } // Copy in the new relations for the new timers. for(int timerNew : newTimers) { for(int timerOld : oldTimers) { // setdbm(newZone.timerIndexToMatrixIndex(timerNew), // newZone.timerIndexToMatrixIndex(timerOld), // tempZone.getdbm(0, timerOld)); // setdbm(newZone.timerIndexToMatrixIndex(timerOld), // newZone.timerIndexToMatrixIndex(timerNew), // tempZone.getdbm(timerOld, 0)); newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld))); newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0)); } } // Set the upper and lower bounds for the new timers. LhpnFile lpn = state.getLpn(); // Associate the Transition with its index. // TreeMap<Integer, Transition> indexToTran = new TreeMap<Integer, Transition>(); // // Get out the Transitions to compare with the enableTran to determine which are // // enabled. // Transition[] allTran = lpn.getAllTransitions(); // for(Transition T : allTran) // int t = T.getIndex(); // if(newTimers.contains(t)) // indexToTran.put(t, T); for(int i : newTimers){ // Get all the upper and lower bounds for the new timers. // Get the name for the timer in the i-th column/row of DBM //String tranName = indexToTran.get(i).getName(); String tranName = _indexToTransition.get(i).getName(); ExprTree delay = lpn.getDelayTree(tranName); // Get the values of the variables for evaluating the ExprTree. HashMap<String, String> varValues = lpn.getAllVarsWithValuesAsString(state.getVector()); // Set the upper and lower bound. int upper, lower; if(delay.getOp().equals("uniform")) { ExprTree lowerDelay = delay.getLeftChild(); ExprTree upperDelay = delay.getRightChild(); lower = (int) lowerDelay.evaluateExpr(varValues); upper = (int) upperDelay.evaluateExpr(varValues); } else { lower = (int) delay.evaluateExpr(varValues); upper = lower; } newZone.setLowerBoundbyTransitionIndex(i, lower); newZone.setUpperBoundbyTransitionIndex(i, upper); } newZone.advance(); newZone.recononicalize(); // Run the test method. //testSplit(newZone, true); //testZoneGraphMinimization(newZone, true); return newZone; } /** * Merges this Zone with another Zone. * @param otherZone * The zone to merge with this Zone. * @return * The merged Zone. */ public ZoneType mergeZones(Zone otherZone) { // TODO: Finish. Zone mergedZone = new Zone(); //mergedZone._indexToTimer = mergeTimers(this._indexToTimer, otherZone._indexToTimer); /* Maps the index of this Zone's timers to the mergedZone. */ //HashMap<Integer, Integer> thisNewIndex; //thisNewIndex = makeIndexMap(this._indexToTimer, mergedZone._indexToTimer); /* Maps the index of otherZone Zone's timers to the mergeZone. */ //HashMap<Integer, Integer> otherNewIndex; //otherNewIndex = makeIndexMap(otherZone._indexToTimer, mergedZone._indexToTimer); //mergedZone._matrix = new int[mergedZone.matrixSize()][mergedZone.matrixSize()]; ZoneTriple[] zoneAndIndex = mergeTimers(otherZone); mergedZone._indexToTimer = new int[zoneAndIndex.length]; for(int i=0; i<zoneAndIndex.length; i++) { mergedZone._indexToTimer[i] = zoneAndIndex[i]._timer; } // Create the matrix for the merged zone. mergedZone._matrix = new int[mergedZone.matrixSize()][mergedZone.matrixSize()]; for(int i=0; i<mergedZone.dbmSize(); i++) { for(int j=0; j<mergedZone.dbmSize(); j++) { // If the timer occurs in both zones to be merged, // then check if the values agree. if(zoneAndIndex[i]._zone2 != null && zoneAndIndex[j]._zone2 != null) { int value1 = this.getDbmEntry(zoneAndIndex[i]._index1, zoneAndIndex[j]._index1); int value2 = otherZone.getDbmEntry(zoneAndIndex[i]._index2, zoneAndIndex[j]._index2); if(value1 != value2) { throw new IncompatibleZoneException("The common timers do not agree."); } else { mergedZone.setDbmEntry(i, j, value1); } } // The timer does not occur in both. else { int iIndex = 0; int jIndex = 0; ZoneType z; // Get the zone with both the timers. if(zoneAndIndex[i]._zone2 != null && zoneAndIndex[i]._zone1 == zoneAndIndex[j]._zone1) { // zoneAndIndex[i] is the timer in a single zone, // and is the same as the first zone in zoneAndIndex. z = zoneAndIndex[i]._zone1; iIndex = zoneAndIndex[i]._index1; jIndex = zoneAndIndex[j]._index1; } else if(zoneAndIndex[i]._zone2 != null && zoneAndIndex[i]._zone1 == zoneAndIndex[j]._zone2) { // zoneAndIndex[i] is the timer in a single zone, // and is the same as the second zone in zoneAndIndex. z = zoneAndIndex[j]._zone1; iIndex = zoneAndIndex[i]._index1; jIndex = zoneAndIndex[j]._index2; } else if(zoneAndIndex[j]._zone2 != null && zoneAndIndex[j]._zone1 == zoneAndIndex[i]._zone1) { // zoneAndIndex[j] is the timer in a single zone, // and is the same as the first zone in zoneAndIndex. z = zoneAndIndex[j]._zone1; iIndex = zoneAndIndex[i]._index1; jIndex = zoneAndIndex[j]._index1; } else { // zoneAndIndex[j] is the timer in a single zone, // and is the same as the second zone in zoneAndIndex. z = zoneAndIndex[j]._zone1; iIndex = zoneAndIndex[i]._index2; jIndex = zoneAndIndex[j]._index1; } mergedZone.setDbmEntry(iIndex, j, z.getDbmEntry(iIndex, jIndex)); } } } return mergedZone; } /** * Merges the timers arrays to give a single sorted timer array. * @param timer1 * The first array to merge. * @param timer2 * The second array to merge. * @return * The merged array. */ // private int[] mergeTimers(int[] timer1, int[] timer2) // /* These integers give the current index of the _indexToTimer. */ // int thisIndex = 1; // int otherIndex = 1; // int newIndex = 1; // // Define an array for merging the timers. // int[] tempTimer = new int[timer1.length + timer2.length + 1]; // while(thisIndex<timer1.length && otherIndex<timer2.length) // if(timer1[thisIndex] == timer2[otherIndex]) // tempTimer[newIndex] = timer1[thisIndex]; // thisIndex++; // otherIndex++; // else if (timer1[thisIndex]<timer2[otherIndex]) // tempTimer[newIndex] = timer1[thisIndex++]; // else // tempTimer[newIndex] = timer2[otherIndex++]; // newIndex++; // if(thisIndex<timer1.length) // while(thisIndex<timer1.length) // tempTimer[newIndex] = timer1[thisIndex]; // newIndex++; // thisIndex++; // else if(otherIndex<timer2.length) // while(otherIndex<timer2.length) // tempTimer[newIndex] = timer2[otherIndex]; // newIndex++; // otherIndex++; // int[] newTimer = new int[newIndex]; // for(int i=1; i<newIndex; i++) // newTimer[i] = tempTimer[i]; // return newTimer; private ZoneTriple[] mergeTimers(Zone otherZone) { /* These integers give the current index of the _indexToTimer. */ int thisIndex = 1; int otherIndex = 1; int newIndex = 1; int thisTimerLength = this._indexToTimer.length; int timer2length = otherZone._indexToTimer.length; // Define an array for merging the timers. ZoneTriple[] tempTimer = new ZoneTriple[thisTimerLength + timer2length + 1]; // The zero is in common to both zones. tempTimer[0] = new ZoneTriple(0, this, 0, otherZone, 0); while(thisIndex<thisTimerLength && otherIndex<timer2length) { if(this._indexToTimer[thisIndex] == otherZone._indexToTimer[otherIndex]) { tempTimer[newIndex] = new ZoneTriple(this._indexToTimer[thisIndex], this, thisIndex, otherZone, otherIndex); thisIndex++; otherIndex++; } else if (this._indexToTimer[thisIndex]<otherZone._indexToTimer[otherIndex]) { tempTimer[newIndex] = new ZoneTriple(this._indexToTimer[thisIndex], this ,thisIndex); thisIndex++; } else { tempTimer[newIndex] = new ZoneTriple(otherZone._indexToTimer[otherIndex], otherZone, otherIndex); otherIndex++; } newIndex++; } if(thisIndex<thisTimerLength) { while(thisIndex<thisTimerLength) { tempTimer[newIndex] = new ZoneTriple(this._indexToTimer[thisIndex], this, thisIndex); newIndex++; thisIndex++; } } else if(otherIndex<timer2length) { while(otherIndex<timer2length) { tempTimer[newIndex] = new ZoneTriple(otherZone._indexToTimer[otherIndex], otherZone, otherIndex); newIndex++; otherIndex++; } } ZoneTriple[] newTimer = new ZoneTriple[newIndex]; for(int i=0; i<newIndex; i++) { newTimer[i] = tempTimer[i]; } return newTimer; } /** * Merges two Zones. * @param firstZone * The first Zone to merge. * @param secondZone * The second Zone to merge. * @return * The merged Zone. */ public static ZoneType mergeZones(Zone firstZone, Zone secondZone) { return firstZone.mergeZones(secondZone); } /** * Maps the indices of a value in one integer array to their indices in another * integer array. * Precondition: The elements in the baseTimers array should be in the newTimers * array. * @param baseTimers * The old order for the integer array. * @param newTimers * The new order for the integer array. * @return * A HashMap that maps the index of a value in the baseTimers array * to its index in the newTimers array. */ private HashMap<Integer, Integer> makeIndexMap(int[] baseTimers, int[] newTimers) { // Map the new index of the timer to the old timer. HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>(); // For the old index, find the new index. for(int i=0; i<baseTimers.length; i++) { newIndex.put(i, Arrays.binarySearch(newTimers, baseTimers[i])); } return newIndex; } /** * Advances time. */ private void advance() { for(int i=0; i<dbmSize(); i++) { _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i); } } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#clone() */ public Zone clone() { // TODO: Check if finished. Zone clonedZone = new Zone(); clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()]; for(int i=0; i<this.matrixSize(); i++) { for(int j=0; j<this.matrixSize(); j++) { clonedZone._matrix[i][j] = this._matrix[i][j]; } } clonedZone._indexToTimer = Arrays.copyOf(_indexToTimer, _indexToTimer.length); clonedZone._hashCode = this._hashCode; return clonedZone; } /** * Restricts the lower bound of a timer. * * @param timer * The timer to tighten the lower bound. */ private void restrict(int timer) { //int dbmIndex = Arrays.binarySearch(_indexToTimer, timer); _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer); } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getEnabledTransitions() */ public List<Transition> getEnabledTransitions() { ArrayList<Transition> enabledTransitions = new ArrayList<Transition>(); // Check if the timer exceeds its lower bound staring with the first nonzero // timer. for(int i=1; i<_indexToTimer.length; i++) { if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) { enabledTransitions.add(_indexToTransition.get(_indexToTimer[i])); } } return enabledTransitions; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.ZoneType#getLexicon() */ public HashMap<Integer, Transition> getLexicon(){ if(_indexToTransition == null){ return null; } return new HashMap<Integer, Transition>(_indexToTransition); } public void setLexicon(HashMap<Integer, Transition> lexicon){ _indexToTransition = lexicon; } /** * Gives an array that maps the index of a timer in the DBM to the timer's index. * @return * The array that maps the index of a timer in the DBM to the timer's index. */ public int[] getIndexToTimer(){ return Arrays.copyOf(_indexToTimer, _indexToTimer.length); } /** * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion. * The intention is for this exception to be thrown is a Zone has a non zero * entry appear on the diagonal. * * @author Andrew N. Fisher * */ public class DiagonalNonZeroException extends java.lang.RuntimeException { /** * Generated serialVersionUID. */ private static final long serialVersionUID = -3857736741611605411L; /** * Creates a DiagonalNonZeroException. * @param Message * The message to be displayed when the exception is thrown. */ public DiagonalNonZeroException(String Message) { super(Message); } } /** * This exception is thrown when trying to merge two zones whose corresponding timers * do not agree. * @author Andrew N. Fisher * */ public class IncompatibleZoneException extends java.lang.RuntimeException { /** * Generated serialVersionUID */ private static final long serialVersionUID = -2453680267411313227L; public IncompatibleZoneException(String Message) { super(Message); } } /** * TODO * @author Andrew N. Fisher * */ private class ZoneTriple { // Representation Invariant: // If both _zone1 and _zone2 are non null, then this Zone should be // in _zone1. private int _timer; private ZoneType _zone1; private int _index1; private ZoneType _zone2; private int _index2; public ZoneTriple (int timer, ZoneType zone, int index) { _timer = timer; _zone1 = zone; _index1 = index; } public ZoneTriple(int timer, ZoneType zone1, int index1, ZoneType zone2, int index2) { _timer = timer; _zone1 = zone1; _index1 = index1; _zone2 = zone2; _index2 = index2; } @SuppressWarnings("unused") public ZoneType get_zone1() { return _zone1; } @SuppressWarnings("unused") public void set_zone1(ZoneType _zone1) { this._zone1 = _zone1; } @SuppressWarnings("unused") public int get_index1() { return _index1; } @SuppressWarnings("unused") public void set_index1(int _index1) { this._index1 = _index1; } @SuppressWarnings("unused") public ZoneType get_zone2() { return _zone2; } @SuppressWarnings("unused") public void set_zone2(ZoneType _zone2) { this._zone2 = _zone2; } @SuppressWarnings("unused") public int get_index2() { return _index2; } @SuppressWarnings("unused") public void set_index2(int _index2) { this._index2 = _index2; } @SuppressWarnings("unused") public int get_timer() { return _timer; } @SuppressWarnings("unused") public void set_timer(int _timer) { this._timer = _timer; } public String toString() { String result= ""; result = "Timer : " + _timer + "\n"; if(_zone2 == null) { result += "In single zone : \n"; result += "********************************\n"; result += _zone1 + "\n"; result += "++++++++++++++++++++++++++++++++\n"; result += "Index : " + _index1 + "\n"; result += "********************************\n"; } else { result += "In both zones : \n"; result += "***First Zone*******************\n"; result += _zone1 + "\n"; result += "++++++++++++++++++++++++++++++++\n"; result += "Index : " + _index1 + "\n"; result += "********************************\n"; result += "***Second Zone*******************\n"; result += _zone2 + "\n"; result += "++++++++++++++++++++++++++++++++\n"; result += "Index : " + _index2 + "\n"; result += "********************************\n"; } return result; } } /** * Tests ways of splitting a zone. * @param z * The Zone to split. * @param popUps * Enables pop up windows notifying that a zone failed. */ private void testSplit(Zone z, boolean popUp) { // Get a new copy of the matrix to manipulate. int[][] m = z._matrix; int[][] newMatrix = new int[m.length][m.length]; // Copy the matrix. for(int i=0; i<m.length; i++) { for(int j=0; j<m.length; j++) { newMatrix[i][j] = m[i][j]; } } boolean evenRow = true; for(int i=2; i<m.length; i++) { for(int j=2; j<m.length; j++, evenRow = !evenRow) { //if(i != j && ((j+1 != i && evenRow) || (i+1 != j && !evenRow))) if(i != j && j+1 != i && i+1 != j) { newMatrix[i][j] = INFINITY; } } } int[] timers = Arrays.copyOfRange(z._indexToTimer, 1, z._indexToTimer.length); Zone newZone = new Zone(timers, newMatrix); if(!z.equals(newZone)) { if(!_FAILURE) { // This is the first failure. _FAILURE = !_FAILURE; if(popUp) { JOptionPane.showMessageDialog(null, "A splitting failure occured." + "See the standard error for more."); } } System.err.println("Method failed for zone:\n" + z); System.err.println("The matrix was"); String result = ""; for(int i=0; i<newZone._matrix.length; i++) { result += "| " + newZone._matrix[i][0]; for(int j=1; j<newZone._matrix.length; j++) { result += ", " + newZone._matrix[i][j]; } result += " |\n"; } System.err.println(result); } } /** * Tests the ZoneGraph storage. * @param z * Zone to test. */ public void testZoneGraphMinimization(Zone z, boolean popUp){ ZoneGraph g = ZoneGraph.extractZoneGraph(z); Zone returnedZone = g.extractZone(); if(!z.equals(returnedZone)){ if(!_FAILURE) { // This is the first failure. _FAILURE = !_FAILURE; if(popUp) { JOptionPane.showMessageDialog(null, "A zone graph failure occured." + "See the standard error for more."); } } System.err.println("Method failed for zone:\n" + z); } } /** * Create a dot file for a graph representing a zone. The graph is a complement graph * on the number of timers. Each timer is a node and the edge from ti to tj is given * the weight x if the (i,j) entry of the DBM is x. * @param write */ public void toDot(PrintStream writer){ // Write the dot file header. writer.println("digraph G {"); // Print the edges. for(int i=0; i<dbmSize(); i++){ for(int j=0; j<dbmSize(); j++){ // No self loops. if(i == j){ continue; } String edge = ""; edge += "\"t" + _indexToTimer[i] + "\""; writer.println("\"t" + _indexToTimer[i] + "\"" + " -> " + "\"t" + _indexToTimer[j] + "\"" + "[label=\"" + getDbmEntry(i,j) + "\"];"); } } // Terminate the main block writer.print("}"); } /** * Clears out the lexicon. */ public static void clearLexicon(){ _indexToTransition = null; } }
package aeronicamc.mods.mxtune.sound; import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MusicPositioned extends MxSound { private static final Logger LOGGER = LogManager.getLogger(MusicPositioned.class); private final Minecraft mc = Minecraft.getInstance(); private int counter; private float lastDistance; MusicPositioned(AudioData audioData) { super(audioData); this.attenuation = AttenuationType.LINEAR; BlockPos blockPos = audioData.getBlockPos(); if (blockPos != null) { this.x = blockPos.getX(); this.y = blockPos.getY(); this.z = blockPos.getZ(); this.stopped = false; this.volume = 1.0F; LOGGER.debug("MusicPositioned BlockPos {}", blockPos); } } @Override protected void onUpdate() { if (audioData != null && audioData.getBlockPos() != null && mc.player != null) { Vector3d thePlayerVec3d = new Vector3d(mc.player.getX(), mc.player.getY(), mc.player.getZ()); float distance = (float) thePlayerVec3d.distanceTo(new Vector3d(this.x, this.y, this.z)); this.volume = (1.0F - MathHelper.clamp(distance / 32.0F, 0.0F, 1.0F)) * audioData.getFadeMultiplier(); if ((counter++ % 20 == 0) && (distance != lastDistance)) { this.lastDistance = distance; } } else { setDonePlaying(); LOGGER.debug("MusicPositioned playID {} done", playID); } } }
package ai.elimu.web.project.app; import ai.elimu.dao.AppCategoryDao; import ai.elimu.dao.AppGroupDao; import java.io.IOException; import java.util.Calendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import ai.elimu.dao.ApplicationDao; import ai.elimu.dao.ApplicationVersionDao; import ai.elimu.dao.ProjectDao; import ai.elimu.model.admin.Application; import ai.elimu.model.admin.ApplicationVersion; import ai.elimu.model.Contributor; import ai.elimu.model.enums.Environment; import ai.elimu.model.enums.admin.ApplicationStatus; import ai.elimu.model.project.AppCategory; import ai.elimu.model.project.AppGroup; import ai.elimu.model.project.Project; import ai.elimu.service.JsonService; import ai.elimu.util.ChecksumHelper; import ai.elimu.util.SlackApiHelper; import ai.elimu.web.context.EnvironmentContextLoaderListener; import java.net.URLEncoder; import java.util.List; import net.dongliu.apk.parser.ByteArrayApkFile; import net.dongliu.apk.parser.bean.ApkMeta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; @Controller @RequestMapping("/project/{projectId}/app-category/{appCategoryId}/app-group/{appGroupId}/app/create") public class AppCreateController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private JsonService jsonService; @Autowired private ProjectDao projectDao; @Autowired private AppCategoryDao appCategoryDao; @Autowired private AppGroupDao appGroupDao; @Autowired private ApplicationDao applicationDao; @Autowired private ApplicationVersionDao applicationVersionDao; @RequestMapping(method = RequestMethod.GET) public String handleRequest( @PathVariable Long projectId, @PathVariable Long appCategoryId, @PathVariable Long appGroupId, @RequestParam(required = false) Long applicationId, Model model ) { logger.info("handleRequest"); Project project = projectDao.read(projectId); model.addAttribute("project", project); AppCategory appCategory = appCategoryDao.read(appCategoryId); model.addAttribute("appCategory", appCategory); AppGroup appGroup = appGroupDao.read(appGroupId); model.addAttribute("appGroup", appGroup); ApplicationVersion applicationVersion = new ApplicationVersion(); logger.info("applicationId: " + applicationId); if (applicationId != null) { Application application = applicationDao.read(applicationId); applicationVersion.setApplication(application); } model.addAttribute("applicationVersion", applicationVersion); return "project/app/create"; } @RequestMapping(method = RequestMethod.POST) public String handleSubmit( ApplicationVersion applicationVersion, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model, HttpSession session, @PathVariable Long appGroupId, @PathVariable Long projectId, @PathVariable Long appCategoryId ) { logger.info("handleSubmit"); Project project = projectDao.read(projectId); AppCategory appCategory = appCategoryDao.read(appCategoryId); AppGroup appGroup = appGroupDao.read(appGroupId); boolean isUpdateOfExistingApplication = applicationVersion.getApplication() != null; logger.info("isUpdateOfExistingApplication: " + isUpdateOfExistingApplication); Contributor contributor = (Contributor) session.getAttribute("contributor"); String packageName = null; if (multipartFile.isEmpty()) { result.rejectValue("bytes", "NotNull"); } else { try { byte[] bytes = multipartFile.getBytes(); Integer fileSizeInKb = bytes.length / 1024; logger.info("fileSizeInKb: " + fileSizeInKb + " (" + (fileSizeInKb / 1024) + "MB)"); String contentType = multipartFile.getContentType(); logger.info("contentType: " + contentType); // Auto-detect applicationId, versionCode, etc. ByteArrayApkFile byteArrayApkFile = new ByteArrayApkFile(bytes); ApkMeta apkMeta = byteArrayApkFile.getApkMeta(); packageName = apkMeta.getPackageName(); logger.info("packageName: " + packageName); String label = apkMeta.getLabel(); logger.info("label: " + label); byte[] icon = byteArrayApkFile.getIconFile().getData(); logger.info("icon.length: " + (icon.length / 1024) + "kB"); Integer versionCode = apkMeta.getVersionCode().intValue(); logger.info("versionCode: " + versionCode); String versionName = apkMeta.getVersionName(); logger.info("versionName: " + versionName); String minSdkVersion = apkMeta.getMinSdkVersion(); logger.info("minSdkVersion: " + minSdkVersion); // Check if Application already exists in the same AppCategory // TODO applicationVersion.setBytes(bytes); applicationVersion.setFileSizeInKb(fileSizeInKb); applicationVersion.setChecksumMd5(ChecksumHelper.calculateMD5(bytes)); applicationVersion.setContentType(contentType); applicationVersion.setVersionCode(versionCode); applicationVersion.setVersionName(versionName); applicationVersion.setLabel(label); applicationVersion.setIcon(icon); // TODO: set minSdkVersion applicationVersion.setTimeUploaded(Calendar.getInstance()); applicationVersion.setContributor(contributor); if (isUpdateOfExistingApplication) { // Verify that the packageName of the new APK matches that of the Application // TODO } if (!isUpdateOfExistingApplication) { // Verify that an Application with identical packageName has not already been uploaded withing the same Project Application existingApplication = applicationDao.readByPackageName(project, packageName); if (existingApplication != null) { result.rejectValue("application", "NonUnique", new String[] {"application"}, null); } } if (isUpdateOfExistingApplication) { // Verify that the versionCode is higher than previous ones List<ApplicationVersion> existingApplicationVersions = applicationVersionDao.readAll(applicationVersion.getApplication()); for (ApplicationVersion existingApplicationVersion : existingApplicationVersions) { if (existingApplicationVersion.getVersionCode() >= applicationVersion.getVersionCode()) { result.rejectValue("versionCode", "TooLow"); break; } } } } catch (IOException ex) { logger.error(ex); } } if (result.hasErrors()) { model.addAttribute("project", project); model.addAttribute("appCategory", appCategory); model.addAttribute("appGroup", appGroup); return "project/app/create"; } else { Application application = applicationVersion.getApplication(); logger.info("application: " + application); if (application == null) { // First-time upload for packageName // Create new Application application = new Application(); application.setLocale(contributor.getLocale()); // TODO: Add Locale to each Project? application.setPackageName(packageName); application.setApplicationStatus(ApplicationStatus.ACTIVE); application.setContributor(contributor); application.setProject(project); applicationDao.create(application); applicationVersion.setApplication(application); applicationVersionDao.create(applicationVersion); appGroup.getApplications().add(application); appGroupDao.update(appGroup); } else { // Update of existing packageName previously uploaded // Create new ApplicationVersion for the existing Application applicationVersionDao.create(applicationVersion); } // Refresh REST API cache // jsonService.refreshApplicationsInAppCollection(appCollection); jsonService.refreshApplicationsInAppCollection(); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String applicationDescription = !isUpdateOfExistingApplication ? "Application" : "APK version"; String text = URLEncoder.encode( contributor.getFirstName() + " just uploaded a new " + applicationDescription + ":\n" + "• Project: \"" + project.getName() + "\"\n" + "• App Category: \"" + appCategory.getName() + "\"\n" + "• Package name: \"" + application.getPackageName() + "\"\n" + "• Version code: " + applicationVersion.getVersionCode() + "\n" + "See ") + "http://elimu.ai/project/" + project.getId() + "/app-category/" + appCategory.getId() + "/app-group/" + appGroup.getId() + "/app/" + application.getId() + "/edit"; SlackApiHelper.postMessage("G6UR7UH2S", text, null, null); } if (!isUpdateOfExistingApplication) { return "redirect:/project/{projectId}/app-category/{appCategoryId}/app-group/{appGroupId}/app/list#" + application.getId(); } else { return "redirect:/project/{projectId}/app-category/{appCategoryId}/app-group/{appGroupId}/app/" + application.getId() + "/edit"; } } } @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException { logger.info("initBinder"); binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); } }
package com.SlothyBear.DungeonMod.Items; import com.SlothyBear.DungeonMod.References.References; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; public class DungeonStaff extends Item { public final String name = References.dungeonStaff; public Integer portal[] = new Integer[3]; public DungeonStaff() { super(); this.setUnlocalizedName(name); this.setCreativeTab(CreativeTabs.MISC); ModItems.registerItem(this, name); } }
package com.athaydes.sparkws; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.Session; import java.io.IOException; /** * Internal class, must be public only so that the Tyrus framework can instantiate it. */ public class InternalSparkWSEndpoint extends Endpoint { @Override public void onOpen( final Session session, EndpointConfig config ) { System.out.println( "Session started on path: " + session.getRequestURI().getPath() ); final EndpointWithOnMessage handler = getHandler( session ); if ( handler == null ) { System.out.println( "No handler found for path " + session.getRequestURI().getPath() ); try { session.close(); } catch ( IOException e ) { e.printStackTrace(); } return; } session.addMessageHandler( new MessageHandler.Whole<String>() { @Override public void onMessage( String message ) { System.out.println( "Server got message " + message ); try { handler.acceptWhole( session, message ); } catch ( IOException e ) { e.printStackTrace(); } } } ); } @Override public void onClose( Session session, CloseReason closeReason ) { final EndpointWithOnMessage handler = getHandler( session ); if ( handler != null ) { handler.onClose( session, closeReason ); } } @Override public void onError( Session session, Throwable thr ) { final EndpointWithOnMessage handler = getHandler( session ); if ( handler != null ) { handler.onError( session, thr ); } } private EndpointWithOnMessage getHandler( Session session ) { return SparkWS.serverInstance.getHandlers().get( session.getRequestURI().getPath().substring( 1 ) ); } }
package com.bebehp.mc.eewreciever.twitter; import java.io.UnsupportedEncodingException; import java.util.LinkedList; import java.util.List; import com.bebehp.mc.eewreciever.EEWRecieverMod; import com.bebehp.mc.eewreciever.ping.AbstractQuakeNode; import com.bebehp.mc.eewreciever.ping.IQuake; import com.bebehp.mc.eewreciever.ping.QuakeException; import twitter4j.Status; import twitter4j.StatusAdapter; import twitter4j.StatusListener; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; public class TweetQuake implements IQuake { private List<AbstractQuakeNode> updatequeue = new LinkedList<AbstractQuakeNode>(); private Configuration configuration; private TwitterStream twitterStream; private StatusListener listener; public TweetQuake() { configuration = new ConfigurationBuilder().setOAuthConsumerKey("mh5mOJhrXkVarLLdNgDn2QFRO") .setOAuthConsumerSecret("NbBfZ5ytY47IniUEOoFOIk0wqfOuByzqMzK26DqvH9GhVL0K3E") .setOAuthAccessToken("4893957312-30hXziVjdX0ZHzH6OJCv0eWAJmaDgyqR7Wwfjob") .setOAuthAccessTokenSecret("ZwqJSMxSFC7lCMmAjgDw3ikwfgnJE9RVyTZt67MYIsMOM").build(); twitterStream = new TwitterStreamFactory(configuration).getInstance(); listener = new StatusAdapter() { @Override public void onStatus(Status status) { try { String str = new String(status.getText().getBytes("UTF-8"), "UTF-8").intern(); updatequeue.add(new TweetQuakeNode().parseString(str)); EEWRecieverMod.logger.info(status.getText()); } catch (UnsupportedEncodingException e) { EEWRecieverMod.logger.error("Encode Error", e); } catch (QuakeException e) { EEWRecieverMod.logger.error("Recieve Error", e); } } }; twitterStream.addListener(listener); twitterStream.user(); } @Override public List<AbstractQuakeNode> getQuakeUpdate() throws QuakeException { if (updatequeue.isEmpty()) return updatequeue; List<AbstractQuakeNode> ret = new LinkedList<AbstractQuakeNode>(updatequeue); updatequeue.clear(); return ret; } }
package com.cliqueup.controllers; import com.cliqueup.entities.ChatMessage; import com.cliqueup.entities.Group; import com.cliqueup.entities.User; import com.cliqueup.services.ChatMessageRepo; import com.cliqueup.services.GroupRepo; import com.cliqueup.services.UserRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.JacksonJsonParser; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import java.util.ArrayList; import java.util.HashMap; @Controller public class WebSocketController { static SimpMessagingTemplate messenger; @Autowired public WebSocketController(SimpMessagingTemplate template) { messenger = template; } @Autowired UserRepo users; @Autowired ChatMessageRepo cms; @Autowired GroupRepo groups; // @MessageMapping("/global") // @SendTo("/global") // public Message message(Message message, HttpSession session) { // String username = (String) session.getAttribute("username"); // User user = users.findByUsername(username); // String text = (String)message.getPayload(); // ChatMessage chatMessage = new ChatMessage(text, user); // cms.save(chatMessage); // return message; // public String room(ArrayList<Group> groups) { // for (Group group : groups) { // String theRoom = group.getName(); // @MessageMapping("/global") // @SendTo("/global") // public Message message(Message message) { // if (new String((byte[]) message.getPayload()).length() > 0) { // HashMap mapper = new HashMap(); // // LinkedHashMap mapper = new LinkedHashMap(); // JacksonJsonParser parser = new JacksonJsonParser(); // Object test = message.getPayload(); // String payload = new String((byte[]) message.getPayload()); // mapper = (HashMap) parser.parseMap(payload); // //mapper = (LinkedHashMap) parser.parseMap(new String((byte[]) message.getPayload())); // //User user = users.findByUsername((String) mapper.get("username")); // User user = users.findByUsername("mike"); // String text = (String) mapper.get("message"); // ChatMessage chatMessage = new ChatMessage(text, user); // cms.save(chatMessage); // // this.messenger.convertAndSend("/global", message); // return message; // return message; @MessageMapping("/global") @SendTo("/global") public ArrayList<String> message (Message message) { if (new String((byte[]) message.getPayload()).length() > 0) { ArrayList<String> myMessage = new ArrayList<>(); HashMap mapper; JacksonJsonParser parser = new JacksonJsonParser(); String payload = new String((byte[]) message.getPayload()); mapper = (HashMap) parser.parseMap(payload); User user = users.findByUsername((String) mapper.get("username")); String text = (String) mapper.get("message"); Group group = new Group("global", "General Chat Channel"); groups.save(group); ChatMessage chatMessage = new ChatMessage(text, group, user); cms.save(chatMessage); myMessage.add(text); myMessage.add(user.getUsername()); return myMessage; } return null; } @MessageMapping("/chat/{groupName}") @SendTo("/chat/{groupName}") public ArrayList<String> groupMessage (Message message) { ArrayList<String> theMessage = new ArrayList<>(); HashMap mapper; JacksonJsonParser parser = new JacksonJsonParser(); String payload = new String((byte[]) message.getPayload()); mapper = (HashMap) parser.parseMap(payload); User user = users.findByUsername((String) mapper.get("username")); String text = (String) mapper.get("message"); String groupName = (String) mapper.get("groupName"); Group group = new Group(groupName, groupName + "chat channel"); groups.save(group); ChatMessage chatMessage = new ChatMessage(text, group, user); cms.save(chatMessage); theMessage.add(text); theMessage.add(user.getUsername()); return theMessage; } }
/* Programmers: Kris Larson Description: The openning interface for players. */ import java.util.*; import java.awt.*; public class TestGameMenu { Scanner input = new Scanner(System.in); public TestGameMenu() { int choice; for (;;) { options(); choice = input.nextInt(); System.out.println(""); switch(choice) { case 1: startGame(); break; case 2: instructions(); break; case 3: about(); break; case 4: futureAdditions(); break; case 5: exitGame(); break; default: System.out.println("INVALID INPUT!\n"); } } } public void options() { System.out.println("\n System.out.print("1) Start Game\n2) Instructions\n3) About\n4) Future Additions\n5) Exit Game\n"); System.out.print("Please enter your choice (1-5): "); } public void startGame() { //Start game :) GameSimulator run = new GameSimulator(); } public void instructions() { boolean loop = true; while (loop) { System.out.println("There were instructions for this thing?"); System.out.print("Enter any key to go back. "); String exit = input.next(); if (!exit.isEmpty()) loop = false; } } public void about() { boolean loop = true; while (loop) { System.out.println("Enter epic and or strange story here."); System.out.print("Enter any key to go back. "); String exit = input.next(); if (!exit.isEmpty()) loop = false; } } public void futureAdditions() { boolean loop = true; while (loop) { System.out.println("Here's a list of things that may be added in the future:"); System.out.print("-Saving\n-Difficulty Options\n-Score Board\n-Achievements\n-Graphical Interface\n"); System.out.print("Enter any key to go back. "); String exit = input.next(); if (!exit.isEmpty()) loop = false; } } public void exitGame() { boolean loop = true; while (loop) { System.out.println("All gameplay will be lost. Are you sure you want to quit (Y/N)? "); String exit = input.next(); if (exit.compareToIgnoreCase("Y") == 0) { System.out.print("Bye!"); System.exit(9); } else if (exit.compareToIgnoreCase("N") == 0) loop = false; else System.out.println("INVALID INPUT!\n"); } } public static void main(String[] args) { TestGameMenu start = new TestGameMenu(); } }
package com.comandante.eyeballs.api; import com.comandante.eyeballs.camera.PictureTakingService; import com.comandante.eyeballs.model.EventsApiResponse; import com.comandante.eyeballs.model.LocalEvent; import com.comandante.eyeballs.storage.LocalEventDatabase; import com.github.sarxos.webcam.Webcam; import com.google.common.collect.Lists; import io.dropwizard.views.View; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; @Path("/") public class EyeballsResource { private final Webcam webcam; private final LocalEventDatabase database; private final PictureTakingService pictureTakingService; public EyeballsResource(Webcam webcam, LocalEventDatabase database, PictureTakingService pictureTakingService) { this.webcam = webcam; this.database = database; this.pictureTakingService = pictureTakingService; } @GET @Path("/image") @Produces("image/png") public Response getImage() throws IOException { return Response.ok(pictureTakingService.getLatestImage()).build(); } @GET @Path("/event/recent") @Produces(MediaType.APPLICATION_JSON) public List<EventsApiResponse> getRecentEvents() throws IOException { List<EventsApiResponse> currentEntries = Lists.newArrayList(); for (LocalEvent next : database.getRecentEvents(10)) { currentEntries.add(new EventsApiResponse(next.getId(), next.getTimestamp())); } Collections.reverse(currentEntries); return currentEntries; } @GET @Path("/event/{eventId}") @Produces("image/jpg") public Response getEventImage(@PathParam("eventId") String eventId) { Optional<LocalEvent> eyeballMotionEvent = database.getEvent(eventId); if (!eyeballMotionEvent.isPresent()) { return Response.status(404).build(); } byte[] pngImageBytes = eyeballMotionEvent.get().getImage(); return Response.ok(pngImageBytes).build(); } @GET @Path("/view/recent_events/{num}") @Produces(MediaType.TEXT_HTML) public View getRecentEventsView(@Context UriInfo uriInfo, @PathParam("num") long num) { return new EventsView(database.getRecentEvents(num), uriInfo); } @GET @Path("/view/recent_events/") @Produces(MediaType.TEXT_HTML) public View getRecentEventsView(@Context UriInfo uriInfo) { EventsView eventsView = new EventsView(database.getRecentEvents(30), uriInfo); return eventsView; } @GET @Path("/view/recent_events/image") @Produces(MediaType.TEXT_HTML) public View getRecentEventsViewImage(@Context UriInfo uriInfo) { EventsView eventsView = new EventsView(database.getRecentEvents(30), uriInfo); eventsView.setDisplayImage(true); return eventsView; } }
package com.elmakers.mine.bukkit.effect; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.security.InvalidParameterException; import java.util.Map; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Effect; import org.bukkit.EntityEffect; import org.bukkit.FireworkEffect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.effect.ParticleType; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; public abstract class EffectPlayer implements com.elmakers.mine.bukkit.api.effect.EffectPlayer { public static boolean initialize(Plugin plugin) { effectLib = EffectLibManager.initialize(plugin); return effectLib != null; } private static EffectLibManager effectLib = null; private ConfigurationSection effectLibConfig = null; private Object currentEffect = null; public static boolean SOUNDS_ENABLED = true; protected Plugin plugin; protected Location origin; protected Location target; protected Vector originOffset; protected Vector targetOffset; protected WeakReference<Entity> originEntity; protected WeakReference<Entity> targetEntity; // These are ignored by the Trail type, need multi-inheritance :\ protected boolean playAtOrigin = true; protected boolean playAtTarget = false; protected Color color = null; protected MaterialAndData material; protected int delayTicks = 0; protected MaterialAndData material1; protected Color color1 = null; protected Color color2 = null; protected EntityEffect entityEffect = null; protected Effect effect = null; protected Integer effectData = null; protected Sound sound = null; protected float soundVolume = 0.7f; protected float soundPitch = 1.5f; protected boolean hasFirework = false; protected FireworkEffect.Type fireworkType; protected int fireworkPower = 1; protected Boolean fireworkFlicker; protected FireworkEffect fireworkEffect; protected ParticleType particleType = null; protected String particleSubType = ""; protected float particleData = 0f; protected float particleXOffset = 0.3f; protected float particleYOffset = 0.3f; protected float particleZOffset = 0.3f; protected int particleCount = 1; protected float scale = 1.0f; protected Vector offset = new Vector(0, 0, 0); public EffectPlayer() { } public EffectPlayer(Plugin plugin) { this.plugin = plugin; } public void load(Plugin plugin, ConfigurationSection configuration) { this.plugin = plugin; if (effectLib != null && configuration.contains("effectlib")) { effectLibConfig = configuration.getConfigurationSection("effectlib"); // I feel like ConfigurationSection should be smart enough for the above // to work, but it is not. // I suspect this is due to having Maps in Lists. Oh well. if (effectLibConfig == null) { Object rawConfig = configuration.get("effectlib"); if (rawConfig instanceof Map) { effectLibConfig = new MemoryConfiguration(); Map<String, Object> map = (Map<String, Object>)rawConfig; for (Map.Entry<String, Object> entry : map.entrySet()) { effectLibConfig.set(entry.getKey(), entry.getValue()); } } else { plugin.getLogger().warning("Could not load effectlib node of type " + rawConfig.getClass()); } } } else { effectLibConfig = null; } originOffset = ConfigurationUtils.getVector(configuration, "origin_offset"); targetOffset = ConfigurationUtils.getVector(configuration, "target_offset"); delayTicks = configuration.getInt("delay", delayTicks) * 20 / 1000; material1 = ConfigurationUtils.getMaterialAndData(configuration, "material"); color1 = ConfigurationUtils.getColor(configuration, "color", null); color2 = ConfigurationUtils.getColor(configuration, "color2", null); if (configuration.contains("effect")) { String effectName = configuration.getString("effect"); effect = Effect.valueOf(effectName.toUpperCase()); if (effect == null) { plugin.getLogger().warning("Unknown effect type " + effectName); } else { effectData = ConfigurationUtils.getInteger(configuration, "effect_data", effectData); } } if (configuration.contains("entity_effect")) { String effectName = configuration.getString("entity_effect"); entityEffect = EntityEffect.valueOf(effectName.toUpperCase()); if (entityEffect == null) { plugin.getLogger().warning("Unknown entity effect type " + effectName); } } if (configuration.contains("sound")) { String soundName = configuration.getString("sound"); sound = Sound.valueOf(soundName.toUpperCase()); if (sound == null) { plugin.getLogger().warning("Unknown sound type " + soundName); } else { soundVolume = (float)configuration.getDouble("sound_volume", soundVolume); soundPitch = (float)configuration.getDouble("sound_pitch", soundPitch); } } if (configuration.contains("firework") || configuration.contains("firework_power")) { hasFirework = true; fireworkType = null; if (configuration.contains("firework")) { String typeName = configuration.getString("firework"); fireworkType = FireworkEffect.Type.valueOf(typeName.toUpperCase()); if (fireworkType == null) { plugin.getLogger().warning("Unknown firework type " + typeName); } } fireworkPower = configuration.getInt("firework_power", fireworkPower); fireworkFlicker = ConfigurationUtils.getBoolean(configuration, "firework_flicker", fireworkFlicker); } if (configuration.contains("particle")) { String typeName = configuration.getString("particle"); particleType = ParticleType.valueOf(typeName.toUpperCase()); if (particleType == null) { plugin.getLogger().warning("Unknown particle type " + typeName); } else { particleSubType = configuration.getString("particle_sub_type", particleSubType); particleData = (float)configuration.getDouble("particle_data", particleData); particleXOffset = (float)configuration.getDouble("particle_offset_x", particleXOffset); particleYOffset = (float)configuration.getDouble("particle_offset_y", particleYOffset); particleZOffset = (float)configuration.getDouble("particle_offset_z", particleZOffset); particleCount = configuration.getInt("particle_count", particleCount); } } setLocationType(configuration.getString("location", "origin")); } public void setLocationType(String locationType) { if (locationType.equals("target")) { playAtOrigin = false; playAtTarget = true; } else if (locationType.equals("origin")) { playAtTarget = false; playAtOrigin = true; } else if (locationType.equals("both")) { playAtTarget = true; playAtOrigin = true; } } public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType) { return getFireworkEffect(color1, color2, fireworkType, null, null); } public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType, Boolean flicker, Boolean trail) { Random rand = new Random(); if (color1 == null) { color1 = Color.fromRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)); } if (color2 == null) { color2 = Color.fromRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)); } if (fireworkType == null) { fireworkType = org.bukkit.FireworkEffect.Type.values()[rand.nextInt(org.bukkit.FireworkEffect.Type.values().length)]; } if (flicker == null) { flicker = rand.nextBoolean(); } if (trail == null) { trail = rand.nextBoolean(); } return FireworkEffect.builder().flicker(flicker).withColor(color1).withFade(color2).with(fireworkType).trail(trail).build(); } public void setEffect(Effect effect) { this.effect = effect; } public void setEntityEffect(EntityEffect entityEffect) { this.entityEffect = entityEffect; } public void setParticleType(ParticleType particleType) { this.particleType = particleType; } public void setParticleSubType(String particleSubType) { this.particleSubType = particleSubType; } public void setEffectData(int data) { this.effectData = data; } @SuppressWarnings("deprecation") protected MaterialAndData getWorkingMaterial() { if (material1 != null) return material1; MaterialAndData result = material; if (result == null && target != null) { result = new MaterialAndData(target.getBlock().getType(), target.getBlock().getData()); } else if (result == null && origin != null) { result = new MaterialAndData(origin.getBlock().getType(), target.getBlock().getData()); } else if (result == null) { result = new MaterialAndData(Material.AIR); } return result; } @SuppressWarnings("deprecation") protected void playEffect(Location targetLocation) { Location location = targetLocation.clone(); location.add(offset); if (effectLib != null && effectLibConfig != null) { currentEffect = effectLib.play(plugin, effectLibConfig, this); } if (effect != null) { int data = effectData == null ? 0 : effectData; if ((effect == Effect.STEP_SOUND) && effectData == null) { Material material = getWorkingMaterial().getMaterial(); // Check for potential bad materials, this can get really hairy (client crashes) if (!material.isSolid()) { return; } data = material.getId(); } location.getWorld().playEffect(location, effect, data); } if (entityEffect != null && originEntity != null && playAtOrigin) { Entity entity = originEntity.get(); if (entity != null) { entity.playEffect(entityEffect); } } if (entityEffect != null && targetEntity != null && playAtTarget) { Entity entity = targetEntity.get(); if (entity != null) { entity.playEffect(entityEffect); } } if (sound != null) { location.getWorld().playSound(location, sound, soundVolume, soundPitch); } if (fireworkEffect != null) { EffectUtils.spawnFireworkEffect(location, fireworkEffect, fireworkPower); } if (particleType != null) { String subType = particleSubType; if ((particleType == ParticleType.BLOCK_BREAKING || particleType == ParticleType.TOOL_BREAKING || particleType == ParticleType.TILE_BREAKING) && particleSubType.length() == 0) { Material material = getWorkingMaterial().getMaterial(); // Check for potential bad materials, this can get really hairy (client crashes) if (particleType == ParticleType.BLOCK_BREAKING && !material.isSolid()) { return; } // TODO: Check for tools... ? if (particleType == ParticleType.TOOL_BREAKING || particleType == ParticleType.TILE_BREAKING) { material = Material.DIAMOND_AXE; } subType = "" + material.getId() + "_" + getWorkingMaterial().getData(); } EffectUtils.playEffect(location, particleType, subType, particleXOffset, particleYOffset, particleZOffset, particleData, particleCount); } } public void setParticleData(float effectData) { this.particleData = effectData; } public void setParticleCount(int particleCount) { this.particleCount = particleCount; } public void setParticleOffset(float xOffset, float yOffset, float zOffset) { this.particleXOffset = xOffset; this.particleYOffset = yOffset; this.particleZOffset = zOffset; } public void setScale(float scale) { this.scale = scale; } public void setSound(Sound sound) { this.sound = sound; } public void setSound(Sound sound, float volume, float pitch) { this.sound = sound; this.soundVolume = volume; this.soundPitch = pitch; } public void setDelayTicks(int ticks) { delayTicks = ticks; } @Override public void start(Entity originEntity, Entity targetEntity) { start(originEntity == null ? null : originEntity.getLocation(), originEntity, targetEntity == null ? null : targetEntity.getLocation(), targetEntity); } @Override public void start(Location origin, Entity originEntity, Location target, Entity targetEntity) { this.originEntity = new WeakReference<Entity>(originEntity); this.targetEntity = new WeakReference<Entity>(targetEntity); start(origin, target); } @Override public void start(Location origin, Location target) { if (origin == null) { throw new InvalidParameterException("Origin cannot be null"); } // Kinda hacky, but makes cross-world trails (e.g. Repair, Backup) work if (target != null && !origin.getWorld().equals(target.getWorld())) { target.setWorld(origin.getWorld()); } this.origin = origin; this.target = target; if (hasFirework) { fireworkEffect = getFireworkEffect(getColor1(), getColor2(), fireworkType, fireworkFlicker, false); } else { fireworkEffect = null; } // Should I let EffectLib handle delay? if (delayTicks > 0 && plugin != null) { final EffectPlayer player = this; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { player.startPlay(); } }, delayTicks); } else { startPlay(); } } protected void checkLocations() { if (origin != null && originOffset != null) { origin = origin.add(originOffset); } if (target != null && targetOffset != null) { target = target.add(targetOffset); } } protected void startPlay() { // Generate a target location for compatibility if none exists. checkLocations(); play(); } protected Vector getDirection() { Vector direction = target == null ? origin.getDirection() : target.toVector().subtract(origin.toVector()); return direction.normalize(); } public void setMaterial(com.elmakers.mine.bukkit.api.block.MaterialAndData material) { this.material = new MaterialAndData(material); } public void setMaterial(Block block) { this.material = new MaterialAndData(block); } public void setColor(Color color) { this.color = color; } public Color getColor1() { return color1 != null ? color1 : color; } public Color getColor2() { return color2 != null ? color2 : color; } public void setOffset(float x, float y, float z) { offset.setX(x); offset.setY(y); offset.setZ(z); } public abstract void play(); public Entity getOriginEntity() { return originEntity == null ? null : originEntity.get(); } public void cancel() { if (currentEffect != null) { if (effectLib != null) { effectLib.cancel(currentEffect); } currentEffect = null; } } }
package com.redhat.ceylon.cmr.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; import java.util.jar.Pack200.Packer; import java.util.jar.Pack200.Unpacker; import java.util.zip.ZipEntry; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.Logger; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.FileUtil; public final class JarUtils { /** A simple filter to determine if an entry should be included in an archive. */ public static interface JarEntryFilter { public boolean avoid(String entryFullName); } public static void finishUpdatingJar(File originalFile, File outputFile, ArtifactContext context, JarOutputStream jarOutputStream, JarEntryFilter filter, RepositoryManager repoManager, boolean verbose, Logger log, Set<String> folders) throws IOException { finishUpdatingJar(originalFile, outputFile, context, jarOutputStream, filter, repoManager, verbose, log, folders, false); } public static void finishUpdatingJar(File originalFile, File outputFile, ArtifactContext context, JarOutputStream jarOutputStream, JarEntryFilter filter, RepositoryManager repoManager, boolean verbose, Logger log, Set<String> folders, boolean pack200) throws IOException { // now copy all previous jar entries if (originalFile != null) { JarFile jarFile = new JarFile(originalFile); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); // skip the old entry if we overwrote it if(filter.avoid(entry.getName())) continue; // only preserve directories if we did not write to them if(entry.isDirectory() && folders.contains(entry.getName())) continue; ZipEntry copiedEntry = new ZipEntry(entry.getName()); // Preserve the modification time and comment copiedEntry.setTime(entry.getTime()); copiedEntry.setComment(entry.getComment()); jarOutputStream.putNextEntry(copiedEntry); if(!entry.isDirectory()){ InputStream inputStream = jarFile.getInputStream(entry); copy(inputStream, jarOutputStream); inputStream.close(); } jarOutputStream.closeEntry(); } jarFile.close(); } // now write all the required directories for(String folder : folders){ ZipEntry dir = new ZipEntry(folder); jarOutputStream.putNextEntry(dir); jarOutputStream.closeEntry(); } jarOutputStream.flush(); jarOutputStream.close(); if(verbose){ log.info("[done writing to jar: "+outputFile.getPath()+"]"); //Log.printLines(log.noticeWriter, "[done writing to jar: "+outputFile.getPath()+"]"); } if (pack200) { repack(outputFile, log); } File sha1File = ShaSigner.sign(outputFile, log, verbose); try { context.setForceOperation(true); repoManager.putArtifact(context, outputFile); ArtifactContext sha1Context = context.getSha1Context(); sha1Context.setForceOperation(true); repoManager.putArtifact(sha1Context, sha1File); } catch(RuntimeException x) { log.error("Failed to write module to repository: "+x.getMessage()); // fatal errors go all the way up but don't print anything if we logged an error throw x; } finally { // now cleanup outputFile.delete(); sha1File.delete(); } } /** * Takes the jar generated file and repacks it using pack200 in an attempt * to reduce the file size. This is only worth doing on jars containing class files. */ private static void repack(File outputFile, Logger log) throws IOException, FileNotFoundException { Packer packer = Pack200.newPacker(); packer.properties().put(Packer.EFFORT, "9"); packer.properties().put(Packer.KEEP_FILE_ORDER, Packer.FALSE); packer.properties().put(Packer.DEFLATE_HINT, Packer.TRUE); packer.properties().put(Packer.SEGMENT_LIMIT, "-1"); packer.properties().put(Packer.MODIFICATION_TIME, Packer.LATEST); File tmp = File.createTempFile("ceylon", "pack200", outputFile.getParentFile()); try { try (OutputStream out = new FileOutputStream(tmp)) { try (JarFile in = new JarFile(outputFile)) { packer.pack(in, out); } } try (JarOutputStream outStream = new JarOutputStream(new FileOutputStream(outputFile))) { outStream.setLevel(9); Unpacker unpacker = Pack200.newUnpacker(); unpacker.unpack(tmp, outStream); } } finally { tmp.delete(); } log.debug("[repacked jar: "+outputFile.getPath()+"]"); } public static String toPlatformIndependentPath(Iterable<? extends File> sourcePaths, String prefixedSourceFile) { String sourceFile = FileUtil.relativeFile(sourcePaths, prefixedSourceFile); // zips are UNIX-friendly sourceFile = sourceFile.replace(File.separatorChar, '/'); return sourceFile; } public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[4096]; int read; while((read = inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, read); } outputStream.flush(); } public static long oldestFileTime(File file) { long mtime = Long.MAX_VALUE; JarFile jarFile = null; try { jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); if (entry.getTime() < mtime) { mtime = entry.getTime(); } } } catch (Exception ex) { mtime = Long.MIN_VALUE; } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { // Ignore } } } return mtime; } public static String getFolder(String fileName) { int lastSep = fileName.lastIndexOf('/'); // toplevel does not need a folder if(lastSep == -1) return null; // include the last slash to create a folder return fileName.substring(0, lastSep+1); } }
package com.github.fluxw42.smappee.api; import java.time.Duration; public enum StateDuration { INFINITE(-1), FIVE_MINUTES(300), FIFTEEN_MINUTES(900), HALF_HOUR(1800), HOUR(3600); /** * The duration in seconds */ private final long duration; /** * Create a new state duration * * @param duration The duration in seconds, or a negative value if not applicable */ StateDuration(final long duration) { this.duration = duration; } /** * Get the duration of an appliance state. A negative value indicates an infinite duration * * @return The duration */ public final Duration getDuration() { return Duration.ofSeconds(this.duration); } }
package com.github.marschal.svndiffstat; import static java.awt.BasicStroke.CAP_ROUND; import static java.awt.BasicStroke.JOIN_ROUND; import static java.awt.Color.WHITE; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static org.jfree.chart.plot.PlotOrientation.VERTICAL; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.text.SimpleDateFormat; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.SortedMap; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYAreaRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.RangeType; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.ui.RectangleInsets; final class ChartBuilder { static final Color DATE_LABEL = new Color(0x33, 0x33, 0x33); static final Color VALUE_LABEL = new Color(0x88, 0x88, 0x88); static final Color TOTAL_LABEL = new Color(0x04, 0x7D, 0xDA); static final Color TOTAL_FILL = new Color(0x04, 0x7D, 0xDA, 127); // also label static final Color DARK_GREY = new Color(0x33, 0x33, 0x33); static final Color ADDED_FILL = new Color(0x1D, 0xB3, 0x4F, 127); // also label static final Color ADDED_STROKE = new Color(0x1D, 0xB3, 0x4F); static final Color REMOVED_FILL = new Color(0xAD, 0x10, 0x17, 127); // also label static final Color REMOVED_STROKE = new Color(0xAD, 0x10, 0x17); static final Color AXIS_LINE_COLOR = new Color(0xEE, 0xEE, 0xEE); static void displayChard(final JFreeChart chart, final DiffStatConfiguration configuration) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(configuration.getDimension()); chartPanel.setDomainZoomable(true); chartPanel.setRangeZoomable(true); JFrame frame = new JFrame("diff-stat"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); } }); } static JFreeChart createChart(NavigableMap<TimeAxisKey, DiffStat> aggregatedDiffstats, DiffStatConfiguration configuration) { boolean legend = false; boolean tooltips = false; boolean urls = false; Font helvetica = new Font("Helvetica", Font.PLAIN, 11 * configuration.multiplierInt()); XYDatasetMinMax datasetMinMax = createDeltaDataset("Additions and Delections", aggregatedDiffstats); XYDataset dataset = datasetMinMax.dataset; JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", dataset, legend, tooltips, urls); chart.setBackgroundPaint(WHITE); chart.setBorderVisible(false); float strokeWidth = 1.2f * configuration.multiplierFloat(); XYPlot plot = chart.getXYPlot(); plot.setOrientation(VERTICAL); plot.setBackgroundPaint(WHITE); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(AXIS_LINE_COLOR); plot.setDomainGridlineStroke(new BasicStroke(1.0f * configuration.multiplierFloat())); plot.setRangeGridlinesVisible(false); plot.setOutlineVisible(false); DateAxis dateAxis = (DateAxis) plot.getDomainAxis(); dateAxis.setDateFormatOverride(new SimpleDateFormat("MM/yy")); dateAxis.setTickLabelFont(helvetica); dateAxis.setAxisLineVisible(false); dateAxis.setTickUnit(computeDateTickUnit(aggregatedDiffstats)); RectangleInsets insets = new RectangleInsets(8.0d * configuration.multiplierDouble(), 4.0d * configuration.multiplierDouble(), 4.0d * configuration.multiplierDouble(), 4.0d * configuration.multiplierDouble()); dateAxis.setTickLabelInsets(insets); NumberAxis additionDeletionAxis = (NumberAxis) plot.getRangeAxis(0); additionDeletionAxis.setAxisLineVisible(false); additionDeletionAxis.setLabel("Additions and Deletions"); additionDeletionAxis.setLabelFont(helvetica); additionDeletionAxis.setTickLabelFont(helvetica); additionDeletionAxis.setRangeType(RangeType.FULL); int lowerBound = datasetMinMax.min + (int) (datasetMinMax.min * 0.1d); additionDeletionAxis.setLowerBound(lowerBound); int upperBound = datasetMinMax.max + (int) (datasetMinMax.max * 0.1d); additionDeletionAxis.setUpperBound(upperBound); additionDeletionAxis.setNumberFormatOverride(new AbbreviatingNumberFormat()); additionDeletionAxis.setMinorTickMarksVisible(false); additionDeletionAxis.setTickMarkInsideLength(5.0f * configuration.multiplierFloat()); additionDeletionAxis.setTickMarkOutsideLength(0.0f); additionDeletionAxis.setTickMarkStroke(new BasicStroke(2.0f * configuration.multiplierFloat())); additionDeletionAxis.setTickUnit(new NumberTickUnit(computeTickUnitSize(datasetMinMax.max + abs(datasetMinMax.min)))); XYAreaRenderer areaRenderer = new XYAreaRenderer(XYAreaRenderer.AREA); areaRenderer.setOutline(true); areaRenderer.setSeriesOutlinePaint(0, ADDED_STROKE); areaRenderer.setSeriesOutlineStroke(0, new BasicStroke(strokeWidth)); areaRenderer.setSeriesPaint(0, ADDED_FILL); areaRenderer.setSeriesOutlinePaint(1, REMOVED_STROKE); areaRenderer.setSeriesOutlineStroke(1, new BasicStroke(strokeWidth)); areaRenderer.setSeriesPaint(1, REMOVED_FILL); plot.setRenderer(0, areaRenderer); // Total Axis NumberAxis totalAxis = new NumberAxis("Total Lines"); totalAxis.setAxisLineVisible(false); totalAxis.setLabelPaint(VALUE_LABEL); totalAxis.setTickLabelPaint(TOTAL_LABEL); totalAxis.setLabelFont(helvetica); totalAxis.setTickLabelFont(helvetica); totalAxis.setNumberFormatOverride(new AbbreviatingNumberFormat()); totalAxis.setMinorTickMarksVisible(false); totalAxis.setTickMarkInsideLength(5.0f * configuration.multiplierFloat()); totalAxis.setTickMarkOutsideLength(0.0f); totalAxis.setTickMarkStroke(new BasicStroke(2.0f * configuration.multiplierFloat())); totalAxis.setTickMarkPaint(TOTAL_LABEL); plot.setRangeAxis(1, totalAxis); plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT); XYDatasetAndMax datasetAndTotal = createTotalDataset("Total Lines", aggregatedDiffstats); XYDataset totalDataSet = datasetAndTotal.dataset; plot.setDataset(1, totalDataSet); plot.mapDatasetToRangeAxis(1, 1); // XYItemRenderer totalRenderer = new XYSplineRenderer(); XYItemRenderer totalRenderer = new StandardXYItemRenderer(); totalRenderer.setSeriesPaint(0, TOTAL_FILL); totalRenderer.setSeriesStroke(0, new BasicStroke(strokeWidth, CAP_ROUND, JOIN_ROUND, 10.0f * configuration.multiplierFloat(), new float[]{6.0f * configuration.multiplierFloat(), 3.0f * configuration.multiplierFloat()} , 0.0f)); plot.setRenderer(1, totalRenderer); totalAxis.setTickUnit(new NumberTickUnit(computeTickUnitSize(datasetAndTotal.max))); return chart; } static DateTickUnit computeDateTickUnit(NavigableMap<TimeAxisKey, DiffStat> aggregatedDiffstats) { TimeAxisKey start = aggregatedDiffstats.firstKey(); TimeAxisKey end = aggregatedDiffstats.lastKey(); int yearsBetween = start.unitsBetween(end, DateTickUnitType.YEAR); if (yearsBetween >= 5) { return new DateTickUnit(DateTickUnitType.YEAR, computeTickUnitSize(yearsBetween)); } int monthsBetween = start.unitsBetween(end, DateTickUnitType.MONTH); if (monthsBetween >= 5) { return new DateTickUnit(DateTickUnitType.MONTH, computeTickUnitSize(monthsBetween)); } // TODO check if day is supported int daysBetween = start.unitsBetween(end, DateTickUnitType.DAY); return new DateTickUnit(DateTickUnitType.DAY, computeTickUnitSize(daysBetween)); } static int computeTickUnitSize(int maximum) { int tenbase = 1; while (tenbase * 10 < maximum) { tenbase *= 10; } int numberOfTicks = maximum / tenbase; if (numberOfTicks == 1) { return tenbase / 10; } else if (numberOfTicks <= 5 && tenbase > 10) { return tenbase / 2; } else { return tenbase; } } private static XYDatasetMinMax createDeltaDataset(String name, SortedMap<TimeAxisKey, DiffStat> aggregatedDiffstats) { TimeSeriesCollection dataset = new TimeSeriesCollection(); int minimum = 0; int maximum = 0; TimeSeries addedSeries = new TimeSeries(name); TimeSeries removedSeries = new TimeSeries(name); for (Entry<TimeAxisKey, DiffStat> entry : aggregatedDiffstats.entrySet()) { TimeAxisKey timeAxisKey = entry.getKey(); DiffStat diffStat = entry.getValue(); RegularTimePeriod period = timeAxisKey.toPeriod(); int added = diffStat.added(); maximum = max(maximum, added); addedSeries.add(period, Integer.valueOf(added)); int removed = -diffStat.removed(); minimum = min(minimum, removed); removedSeries.add(period, Integer.valueOf(removed)); } dataset.addSeries(addedSeries); dataset.addSeries(removedSeries); return new XYDatasetMinMax(dataset, minimum, maximum); } private static XYDatasetAndMax createTotalDataset(String name, SortedMap<TimeAxisKey, DiffStat> aggregatedDiffstats) { int total = 0; int max = Integer.MIN_VALUE; TimeSeries totalSeries = new TimeSeries(name); for (Entry<TimeAxisKey, DiffStat> entry : aggregatedDiffstats.entrySet()) { TimeAxisKey timeAxisKey = entry.getKey(); DiffStat diffStat = entry.getValue(); RegularTimePeriod period = timeAxisKey.toPeriod(); total += diffStat.delta(); max = max(total, max); totalSeries.add(period, Integer.valueOf(total)); } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(totalSeries); return new XYDatasetAndMax(dataset, max); } static final class XYDatasetMinMax { final XYDataset dataset; final int min; final int max; XYDatasetMinMax(XYDataset dataset, int min, int max) { this.dataset = dataset; this.min = min; this.max = max; } } static final class XYDatasetAndMax { final XYDataset dataset; final int max; XYDatasetAndMax(XYDataset dataset, int total) { this.dataset = dataset; this.max = total; } } }
package com.gmail.nossr50.listeners; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.inventory.ItemStack; import com.gmail.nossr50.Combat; import com.gmail.nossr50.Users; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.LoadProperties; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.datatypes.SkillType; import com.gmail.nossr50.locale.mcLocale; import com.gmail.nossr50.party.Party; import com.gmail.nossr50.skills.Acrobatics; import com.gmail.nossr50.skills.BlastMining; import com.gmail.nossr50.skills.Skills; import com.gmail.nossr50.skills.Taming; public class mcEntityListener implements Listener { private final mcMMO plugin; public mcEntityListener(final mcMMO plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { //Check for world pvp flag if(event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent eventb = (EntityDamageByEntityEvent)event; if(eventb.getEntity() instanceof Player && eventb.getDamager() instanceof Player && !event.getEntity().getWorld().getPVP()) return; } /* * CHECK FOR INVULNERABILITY */ if(event.getEntity() instanceof Player) { Player defender = (Player)event.getEntity(); PlayerProfile PPd = Users.getProfile(defender); if(defender != null && PPd.getGodMode()) event.setCancelled(true); if(PPd == null) Users.addUser(defender); } /* * Demolitions Expert */ if(event.getCause() == DamageCause.BLOCK_EXPLOSION) { if(event.getEntity() instanceof Player) { Player player = (Player)event.getEntity(); BlastMining.demolitionsExpertise(player, event); } } if(event.getEntity() instanceof LivingEntity) { { LivingEntity entityliving = (LivingEntity)event.getEntity(); if(entityliving.getNoDamageTicks() < entityliving.getMaximumNoDamageTicks()/2.0F) { Entity x = event.getEntity(); DamageCause type = event.getCause(); if(event.getEntity() instanceof Wolf && ((Wolf)event.getEntity()).isTamed() && Taming.getOwner(((Wolf)event.getEntity()), plugin) != null) { Wolf theWolf = (Wolf) event.getEntity(); Player master = Taming.getOwner(theWolf, plugin); PlayerProfile PPo = Users.getProfile(master); if(master == null || PPo == null) return; //Environmentally Aware if((event.getCause() == DamageCause.CONTACT || event.getCause() == DamageCause.LAVA || event.getCause() == DamageCause.FIRE) && PPo.getSkillLevel(SkillType.TAMING) >= 100) { if(event.getDamage() < ((Wolf) event.getEntity()).getHealth()) { event.getEntity().teleport(Taming.getOwner(theWolf, plugin).getLocation()); master.sendMessage(mcLocale.getString("mcEntityListener.WolfComesBack")); //$NON-NLS-1$ event.getEntity().setFireTicks(0); } } if(event.getCause() == DamageCause.FALL && PPo.getSkillLevel(SkillType.TAMING) >= 100) { event.setCancelled(true); } //Thick Fur if(event.getCause() == DamageCause.FIRE_TICK) { event.getEntity().setFireTicks(0); } } /* * ACROBATICS */ if(x instanceof Player){ Player player = (Player)x; if(type == DamageCause.FALL){ Acrobatics.acrobaticsCheck(player, event); } } /* * Entity Damage by Entity checks */ if(event instanceof EntityDamageByEntityEvent && !event.isCancelled()) { EntityDamageByEntityEvent eventb = (EntityDamageByEntityEvent) event; Entity f = eventb.getDamager(); Entity e = event.getEntity(); /* * PARTY CHECKS */ if(e instanceof Player && f instanceof Player) { Player defender = (Player)e; Player attacker = (Player)f; if(Party.getInstance().inSameParty(defender, attacker)) event.setCancelled(true); } Combat.combatChecks(event, plugin); } /* * Check to see if the defender took damage so we can apply recently hurt */ if(event.getEntity() instanceof Player) { Player herpderp = (Player)event.getEntity(); if(!event.isCancelled() && event.getDamage() >= 1) { Users.getProfile(herpderp).setRecentlyHurt(System.currentTimeMillis()); } } } } } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { Entity x = event.getEntity(); x.setFireTicks(0); //Remove bleed track if(plugin.misc.bleedTracker.contains((LivingEntity)x)) plugin.misc.addToBleedRemovalQue((LivingEntity)x); Skills.arrowRetrievalCheck(x, plugin); if(x instanceof Player){ Player player = (Player)x; Users.getProfile(player).setBleedTicks(0); } } @EventHandler public void onCreatureSpawn(CreatureSpawnEvent event) { SpawnReason reason = event.getSpawnReason(); if(reason == SpawnReason.SPAWNER && !LoadProperties.xpGainsMobSpawners) { plugin.misc.mobSpawnerList.add(event.getEntity()); } } @EventHandler (priority = EventPriority.LOW) public void onExplosionPrime(ExplosionPrimeEvent event) { if(event.getEntity() instanceof TNTPrimed) { Block block = event.getEntity().getLocation().getBlock(); if(plugin.misc.tntTracker.get(block) != null) { int skillLevel = plugin.misc.tntTracker.get(block); BlastMining.biggerBombs(skillLevel, event); } } } @EventHandler (priority = EventPriority.LOW) public void onEnitityExplode(EntityExplodeEvent event) { if(event.getEntity() instanceof TNTPrimed) { Block block = event.getLocation().getBlock(); if(plugin.misc.tntTracker.get(block) != null) { int skillLevel = plugin.misc.tntTracker.get(block); BlastMining.dropProcessing(skillLevel, event, plugin); } } } @EventHandler (priority = EventPriority.MONITOR) public void onFoodLevelChange(FoodLevelChangeEvent event) { if(event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); PlayerProfile PP = Users.getProfile(player); int currentFoodLevel = player.getFoodLevel(); int newFoodLevel = event.getFoodLevel(); if(newFoodLevel > currentFoodLevel) { int food = player.getItemInHand().getTypeId(); if(food == 297 || food == 357 || food == 360 || food == 282) { int foodChange = newFoodLevel - currentFoodLevel; int herbLevel = PP.getSkillLevel(SkillType.HERBALISM); if(herbLevel < 200) foodChange = foodChange + 1; if(herbLevel >= 200 || herbLevel < 400) foodChange = foodChange + 2; if(herbLevel >= 400 || herbLevel < 600) foodChange = foodChange + 3; if(herbLevel >= 600 || herbLevel < 800) foodChange = foodChange + 4; if(herbLevel >= 800 || herbLevel < 1000) foodChange = foodChange + 5; if(herbLevel >= 1000) foodChange = foodChange + 6; newFoodLevel = currentFoodLevel + foodChange; if(newFoodLevel > 20) event.setFoodLevel(20); if(newFoodLevel <= 20) event.setFoodLevel(newFoodLevel); } } } } public boolean isBow(ItemStack is){ if (is.getTypeId() == 261){ return true; } else { return false; } } public boolean isPlayer(Entity entity){ if (entity instanceof Player) { return true; } else{ return false; } } }
package com.gocardless.services; import java.util.Map; import com.gocardless.http.*; import com.gocardless.resources.MandateImport; import com.google.common.collect.ImmutableMap; import com.google.gson.annotations.SerializedName; /** * Service class for working with mandate import resources. * * Mandate Imports allow you to migrate existing mandates from other providers into the * GoCardless platform. * * The process is as follows: * * 1. [Create a mandate import](#mandate-imports-create-a-new-mandate-import) * 2. [Add entries](#mandate-import-entries-add-a-mandate-import-entry) to the import * 3. [Submit](#mandate-imports-submit-a-mandate-import) the import * 4. Wait until a member of the GoCardless team approves the import, at which point the mandates * will be created * 5. [Link up the mandates](#mandate-import-entries-list-all-mandate-import-entries) in your * system * * When you add entries to your mandate import, they are not turned into actual mandates * until the mandate import is submitted by you via the API, and then processed by a member * of the GoCardless team. When that happens, a mandate will be created for each entry in the import. * * We will issue a `mandate_created` webhook for each entry, which will be the same as the webhooks * triggered when [ creating a mandate ](#mandates-create-a-mandate) using the mandates API. Once * these * webhooks start arriving, any reconciliation can now be accomplished by * [checking the current status](#mandate-imports-get-a-mandate-import) of the mandate import and * [linking up the mandates to your system](#mandate-import-entries-list-all-mandate-import-entries). * * <p class="notice">Note that all Mandate Imports have an upper limit of 30,000 entries, so * we recommend you split your import into several smaller imports if you're planning to * exceed this threshold.</p> * * <p class="restricted-notice"><strong>Restricted</strong>: This API is currently * only available for approved integrators - please <a href="mailto:help@gocardless.com">get * in touch</a> if you would like to use this API.</p> */ public class MandateImportService { private final HttpClient httpClient; /** * Constructor. Users of this library should have no need to call this - an instance * of this class can be obtained by calling {@link com.gocardless.GoCardlessClient#mandateImports() }. */ public MandateImportService(HttpClient httpClient) { this.httpClient = httpClient; } /** * Mandate imports are first created, before mandates are added one-at-a-time, so * this endpoint merely signals the start of the import process. Once you've finished * adding entries to an import, you should * [submit](#mandate-imports-submit-a-mandate-import) it. */ public MandateImportCreateRequest create() { return new MandateImportCreateRequest(httpClient); } /** * Returns a single mandate import. */ public MandateImportGetRequest get(String identity) { return new MandateImportGetRequest(httpClient, identity); } /** * Submits the mandate import, which allows it to be processed by a member of the * GoCardless team. Once the import has been submitted, it can no longer have entries * added to it. * * In our sandbox environment, to aid development, we automatically process mandate * imports approximately 10 seconds after they are submitted. This will allow you to * test both the "submitted" response and wait for the webhook to confirm the * processing has begun. */ public MandateImportSubmitRequest submit(String identity) { return new MandateImportSubmitRequest(httpClient, identity); } /** * Cancels the mandate import, which aborts the import process and stops the mandates * being set up in GoCardless. Once the import has been cancelled, it can no longer have * entries added to it. Mandate imports which have already been submitted or processed * cannot be cancelled. */ public MandateImportCancelRequest cancel(String identity) { return new MandateImportCancelRequest(httpClient, identity); } /** * Request class for {@link MandateImportService#create }. * * Mandate imports are first created, before mandates are added one-at-a-time, so * this endpoint merely signals the start of the import process. Once you've finished * adding entries to an import, you should * [submit](#mandate-imports-submit-a-mandate-import) it. */ public static final class MandateImportCreateRequest extends IdempotentPostRequest<MandateImport> { private Scheme scheme; /** * A Direct Debit scheme. Currently "autogiro", "bacs", "becs", betalingsservice", and "sepa_core" * are supported. */ public MandateImportCreateRequest withScheme(Scheme scheme) { this.scheme = scheme; return this; } public MandateImportCreateRequest withIdempotencyKey(String idempotencyKey) { super.setIdempotencyKey(idempotencyKey); return this; } @Override protected GetRequest<MandateImport> handleConflict(HttpClient httpClient, String id) { MandateImportGetRequest request = new MandateImportGetRequest(httpClient, id); for (Map.Entry<String, String> header : this.getCustomHeaders().entrySet()) { request = request.withHeader(header.getKey(), header.getValue()); } return request; } private MandateImportCreateRequest(HttpClient httpClient) { super(httpClient); } public MandateImportCreateRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected String getPathTemplate() { return "mandate_imports"; } @Override protected String getEnvelope() { return "mandate_imports"; } @Override protected Class<MandateImport> getResponseClass() { return MandateImport.class; } @Override protected boolean hasBody() { return true; } public enum Scheme { @SerializedName("autogiro") AUTOGIRO, @SerializedName("bacs") BACS, @SerializedName("becs") BECS, @SerializedName("betalingsservice") BETALINGSSERVICE, @SerializedName("sepa_core") SEPA_CORE; @Override public String toString() { return name().toLowerCase(); } } } /** * Request class for {@link MandateImportService#get }. * * Returns a single mandate import. */ public static final class MandateImportGetRequest extends GetRequest<MandateImport> { @PathParam private final String identity; private MandateImportGetRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public MandateImportGetRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected Map<String, Object> getQueryParams() { ImmutableMap.Builder<String, Object> params = ImmutableMap.builder(); params.putAll(super.getQueryParams()); return params.build(); } @Override protected String getPathTemplate() { return "mandate_imports/:identity"; } @Override protected String getEnvelope() { return "mandate_imports"; } @Override protected Class<MandateImport> getResponseClass() { return MandateImport.class; } } /** * Request class for {@link MandateImportService#submit }. * * Submits the mandate import, which allows it to be processed by a member of the * GoCardless team. Once the import has been submitted, it can no longer have entries * added to it. * * In our sandbox environment, to aid development, we automatically process mandate * imports approximately 10 seconds after they are submitted. This will allow you to * test both the "submitted" response and wait for the webhook to confirm the * processing has begun. */ public static final class MandateImportSubmitRequest extends PostRequest<MandateImport> { @PathParam private final String identity; private MandateImportSubmitRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public MandateImportSubmitRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "mandate_imports/:identity/actions/submit"; } @Override protected String getEnvelope() { return "mandate_imports"; } @Override protected Class<MandateImport> getResponseClass() { return MandateImport.class; } @Override protected boolean hasBody() { return true; } @Override protected String getRequestEnvelope() { return "data"; } } /** * Request class for {@link MandateImportService#cancel }. * * Cancels the mandate import, which aborts the import process and stops the mandates * being set up in GoCardless. Once the import has been cancelled, it can no longer have * entries added to it. Mandate imports which have already been submitted or processed * cannot be cancelled. */ public static final class MandateImportCancelRequest extends PostRequest<MandateImport> { @PathParam private final String identity; private MandateImportCancelRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public MandateImportCancelRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "mandate_imports/:identity/actions/cancel"; } @Override protected String getEnvelope() { return "mandate_imports"; } @Override protected Class<MandateImport> getResponseClass() { return MandateImport.class; } @Override protected boolean hasBody() { return true; } @Override protected String getRequestEnvelope() { return "data"; } } }
package com.hankcs.hanlp.dictionary; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.collection.AhoCorasick.AhoCorasickDoubleArrayTrie; import com.hankcs.hanlp.collection.trie.DoubleArrayTrie; import com.hankcs.hanlp.collection.trie.bintrie.BinTrie; import com.hankcs.hanlp.corpus.io.ByteArray; import com.hankcs.hanlp.corpus.tag.Nature; import com.hankcs.hanlp.dictionary.other.CharTable; import com.hankcs.hanlp.utility.Predefine; import java.io.*; import java.util.*; import static com.hankcs.hanlp.utility.Predefine.logger; /** * * * @author He Han */ public class CustomDictionary { /** * trie */ public static BinTrie<CoreDictionary.Attribute> trie; public static DoubleArrayTrie<CoreDictionary.Attribute> dat = new DoubleArrayTrie<CoreDictionary.Attribute>(); public final static String path[] = HanLP.Config.CustomDictionaryPath; static { long start = System.currentTimeMillis(); if (!loadMainDictionary(path[0])) { logger.warning("" + Arrays.toString(path) + ""); } else { logger.info(":" + dat.size() + "" + (System.currentTimeMillis() - start) + "ms"); } } private static boolean loadMainDictionary(String mainPath) { logger.info(":" + mainPath); if (loadDat(mainPath)) return true; TreeMap<String, CoreDictionary.Attribute> map = new TreeMap<String, CoreDictionary.Attribute>(); try { for (String p : path) { Nature defaultNature = Nature.n; int cut = p.indexOf(' '); if (cut > 0) { String nature = p.substring(cut + 1); p = p.substring(0, cut); try { defaultNature = Nature.valueOf(nature); } catch (Exception e) { logger.severe("" + p + "" + e); continue; } } logger.info("[" + defaultNature + "]" + p + "……"); boolean success = load(p, defaultNature, map); if (!success) logger.warning("" + p); } logger.info("DoubleArrayTrie……"); dat.build(map); // dat logger.info("dat……"); List<CoreDictionary.Attribute> attributeList = new LinkedList<CoreDictionary.Attribute>(); for (Map.Entry<String, CoreDictionary.Attribute> entry : map.entrySet()) { attributeList.add(entry.getValue()); } DataOutputStream out = new DataOutputStream(new FileOutputStream(mainPath + Predefine.BIN_EXT)); out.writeInt(attributeList.size()); for (CoreDictionary.Attribute attribute : attributeList) { out.writeInt(attribute.totalFrequency); out.writeInt(attribute.nature.length); for (int i = 0; i < attribute.nature.length; ++i) { out.writeInt(attribute.nature[i].ordinal()); out.writeInt(attribute.frequency[i]); } } dat.save(out); out.close(); } catch (FileNotFoundException e) { logger.severe("" + mainPath + "" + e); return false; } catch (IOException e) { logger.severe("" + mainPath + "" + e); return false; } catch (Exception e) { logger.warning("" + mainPath + "" + e); } return true; } /** * * * @param path * @param defaultNature * @return */ public static boolean load(String path, Nature defaultNature, TreeMap<String, CoreDictionary.Attribute> map) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { String[] param = line.split("\\s"); if (param[0].length() == 0) continue; if (HanLP.Config.Normalization) param[0] = CharTable.convert(param[0]); // if (CoreDictionary.contains(param[0]) || map.containsKey(param[0])) // continue; int natureCount = (param.length - 1) / 2; CoreDictionary.Attribute attribute; if (natureCount == 0) { attribute = new CoreDictionary.Attribute(defaultNature); } else { attribute = new CoreDictionary.Attribute(natureCount); for (int i = 0; i < natureCount; ++i) { attribute.nature[i] = Enum.valueOf(Nature.class, param[1 + 2 * i]); attribute.frequency[i] = Integer.parseInt(param[2 + 2 * i]); attribute.totalFrequency += attribute.frequency[i]; } } map.put(param[0], attribute); } br.close(); } catch (Exception e) { logger.severe("" + path + "" + e); return false; } return true; } public static boolean add(String word, String natureWithFrequency) { if (contains(word)) return false; return insert(word, natureWithFrequency); } public static boolean add(String word) { if (HanLP.Config.Normalization) word = CharTable.convert(word); if (contains(word)) return false; return insert(word, null); } public static boolean insert(String word, String natureWithFrequency) { if (word == null) return false; if (HanLP.Config.Normalization) word = CharTable.convert(word); CoreDictionary.Attribute att = natureWithFrequency == null ? new CoreDictionary.Attribute(Nature.nz, 1) : CoreDictionary.Attribute.create(natureWithFrequency); if (att == null) return false; if (dat.set(word, att)) return true; if (trie == null) trie = new BinTrie<CoreDictionary.Attribute>(); trie.put(word, att); return true; } /** * * * @param word * @return */ public static boolean insert(String word) { return insert(word, null); } /** * * * @param path * @return */ static boolean loadDat(String path) { try { ByteArray byteArray = ByteArray.createByteArray(path + Predefine.BIN_EXT); int size = byteArray.nextInt(); CoreDictionary.Attribute[] attributes = new CoreDictionary.Attribute[size]; final Nature[] natureIndexArray = Nature.values(); for (int i = 0; i < size; ++i) { int currentTotalFrequency = byteArray.nextInt(); int length = byteArray.nextInt(); attributes[i] = new CoreDictionary.Attribute(length); attributes[i].totalFrequency = currentTotalFrequency; for (int j = 0; j < length; ++j) { attributes[i].nature[j] = natureIndexArray[byteArray.nextInt()]; attributes[i].frequency[j] = byteArray.nextInt(); } } if (!dat.load(byteArray, attributes) || byteArray.hasMore()) return false; } catch (Exception e) { logger.warning("" + e); return false; } return true; } /** * * * @param key * @return */ public static CoreDictionary.Attribute get(String key) { if (HanLP.Config.Normalization) key = CharTable.convert(key); CoreDictionary.Attribute attribute = dat.get(key); if (attribute != null) return attribute; if (trie == null) return null; return trie.get(key); } /** * * * @param key */ public static void remove(String key) { if (HanLP.Config.Normalization) key = CharTable.convert(key); if (trie == null) return; trie.remove(key); } /** * * * @param key * @return */ public static LinkedList<Map.Entry<String, CoreDictionary.Attribute>> commonPrefixSearch(String key) { return trie.commonPrefixSearchWithValue(key); } /** * * * @param chars * @param begin * @return */ public static LinkedList<Map.Entry<String, CoreDictionary.Attribute>> commonPrefixSearch(char[] chars, int begin) { return trie.commonPrefixSearchWithValue(chars, begin); } public static BaseSearcher getSearcher(String text) { return new Searcher(text); } @Override public String toString() { return "CustomDictionary{" + "trie=" + trie + '}'; } /** * * @param key * @return */ public static boolean contains(String key) { if (dat.exactMatchSearch(key) >= 0) return true; return trie != null && trie.containsKey(key); } /** * BinTrie * @param charArray * @return */ public static BaseSearcher getSearcher(char[] charArray) { return new Searcher(charArray); } static class Searcher extends BaseSearcher<CoreDictionary.Attribute> { int begin; private LinkedList<Map.Entry<String, CoreDictionary.Attribute>> entryList; protected Searcher(char[] c) { super(c); entryList = new LinkedList<Map.Entry<String, CoreDictionary.Attribute>>(); } protected Searcher(String text) { super(text); entryList = new LinkedList<Map.Entry<String, CoreDictionary.Attribute>>(); } @Override public Map.Entry<String, CoreDictionary.Attribute> next() { while (entryList.size() == 0 && begin < c.length) { entryList = trie.commonPrefixSearchWithValue(c, begin); ++begin; } if (entryList.size() == 0 && begin < c.length) { entryList = trie.commonPrefixSearchWithValue(c, begin); ++begin; } if (entryList.size() == 0) { return null; } Map.Entry<String, CoreDictionary.Attribute> result = entryList.getFirst(); entryList.removeFirst(); offset = begin - 1; return result; } } /** * trie * * @return * @deprecated */ public static BinTrie<CoreDictionary.Attribute> getTrie() { return trie; } /** * BinTrie+DAT * @param text * @param processor */ public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { if (trie != null) { BaseSearcher searcher = CustomDictionary.getSearcher(text); int offset; Map.Entry<String, CoreDictionary.Attribute> entry; while ((entry = searcher.next()) != null) { offset = searcher.getOffset(); processor.hit(offset, offset + entry.getKey().length(), entry.getValue()); } } DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } } }
package injection; import java.io.IOException; import java.io.Writer; import java.util.*; import java.lang.reflect.Modifier; import persistence.SystemException; import persistence.UniqueViolationException; public final class Instrumentor implements InjectionConsumer { private final Writer output; /** * Holds several properties of the class currently * worked on. */ private JavaClass class_state=null; /** * Collects the class states of outer classes, * when operating on a inner class. * @see #class_state * @element-type InstrumentorClass */ private ArrayList class_state_stack=new ArrayList(); protected final String lineSeparator; /** * The last file level doccomment that was read. */ private String lastFileDocComment = null; public Instrumentor(Writer output) { this.output=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public void onPackage(JavaFile javafile) throws InjectorParseException { } public void onImport(String importname) { } private boolean discardnextfeature=false; /** * Tag name for persistent classes. */ private static final String PERSISTENT_CLASS = "persistent"; /** * Tag name for persistent attributes. */ private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS; /** * Tag name for unique attributes. */ private static final String UNIQUE_ATTRIBUTE = "unique"; /** * Tag name for read-only attributes. */ private static final String READ_ONLY_ATTRIBUTE = "read-only"; /** * Tag name for one qualifier of qualified attributes. */ private static final String ATTRIBUTE_QUALIFIER = "qualifier"; /** * All generated class features get this doccomment tag. */ private static final String GENERATED = "generated"; private void handleClassComment(final JavaClass jc, final String docComment) { if(containsTag(docComment, PERSISTENT_CLASS)) jc.setPersistent(); } public void onClass(final JavaClass jc) { //System.out.println("onClass("+jc.getName()+")"); discardnextfeature=false; class_state_stack.add(class_state); class_state=jc; if(lastFileDocComment != null) { handleClassComment(jc, lastFileDocComment); lastFileDocComment = null; } } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeParameterDeclarationList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write("final "); output.write(parameter); output.write(' '); output.write(lowerCamelCase(parameter)); } } } private void writeParameterCallList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write(lowerCamelCase(parameter)); } } } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { output.write(" throws "); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); output.write(((Class)i.next()).getName()); } } } private final void writeCommentHeader() throws IOException { output.write("/**"); output.write(lineSeparator); output.write(lineSeparator); output.write("\t **"); output.write(lineSeparator); } private final void writeCommentFooter() throws IOException { output.write("\t * @"+GENERATED); output.write(lineSeparator); output.write("\t *"); output.write(lineSeparator); output.write(" */"); } public void writeConstructor(final JavaClass javaClass) throws IOException { writeCommentHeader(); output.write("\t * This is a generated constructor."); output.write(lineSeparator); writeCommentFooter(); output.write(Modifier.toString(javaClass.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE))); output.write(' '); output.write(javaClass.getName()); output.write('('); boolean first = true; final ArrayList readOnlyAttributes = new ArrayList(); final TreeSet setterExceptions = new TreeSet(); for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); ) { final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); if(persistentAttribute.isReadOnly()) { readOnlyAttributes.add(persistentAttribute); setterExceptions.addAll(persistentAttribute.getSetterExceptions()); if(first) first = false; else output.write(','); output.write("final "); output.write(persistentAttribute.getPersistentType()); output.write(' '); output.write(persistentAttribute.getName()); } } output.write(')'); writeThrowsClause(setterExceptions); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(1.0);"); output.write(lineSeparator); for(Iterator i = readOnlyAttributes.iterator(); i.hasNext(); ) { final JavaAttribute readOnlyAttribute = (JavaAttribute)i.next(); output.write("\t\tset"); output.write(readOnlyAttribute.getCamelCaseName()); output.write('('); output.write(readOnlyAttribute.getName()); output.write(");"); output.write(lineSeparator); } output.write("\t}"); } private void writeAccessMethods(final JavaAttribute persistentAttribute) throws IOException { final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()); final String type = persistentAttribute.getPersistentType(); final List qualifiers = persistentAttribute.getQualifiers(); // getter writeCommentHeader(); output.write("\t * Returns the value of the persistent attribute {@link output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(type); output.write(" get"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); writeParameterDeclarationList(qualifiers); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeGetterBody(output, persistentAttribute); output.write("\t}"); // setter writeCommentHeader(); output.write("\t * Sets a new value for the persistent attribute {@link output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(" void set"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final "); output.write(type); output.write(' '); output.write(persistentAttribute.getName()); output.write(')'); writeThrowsClause(persistentAttribute.getSetterExceptions()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeSetterBody(output, persistentAttribute); output.write("\t}"); } private void writeUniqueFinder(final JavaAttribute[] persistentAttributes) throws IOException { final JavaAttribute persistentAttribute = persistentAttributes[0]; final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()|Modifier.STATIC); final String type = persistentAttribute.getPersistentType(); final List qualifiers = persistentAttribute.getQualifiers(); final String name = persistentAttribute.getCamelCaseName(); writeCommentHeader(); output.write("\t * Finds a "); output.write(lowerCamelCase(persistentAttributes[0].getParent().getName())); output.write(" by it's unique attributes"); output.write(lineSeparator); output.write("\t * @param "); output.write(persistentAttribute.getName()); output.write(" shall be equal to attribute {@link output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(persistentAttribute.getParent().getName()); output.write(" findBy"); output.write(name); output.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final "); output.write(type); output.write(' '); output.write(persistentAttribute.getName()); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\treturn null;"); output.write(lineSeparator); output.write("\t}"); } public void onClassEnd(JavaClass jc) throws IOException, InjectorParseException { //System.out.println("onClassEnd("+jc.getName()+")"); if(!jc.isInterface() && jc.isPersistent()) { writeConstructor(jc); for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); writeAccessMethods(persistentAttribute); } for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); ) { // write unique finder methods final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); if(persistentAttribute.isUnique()) writeUniqueFinder(new JavaAttribute[]{persistentAttribute}); } } if(class_state!=jc) throw new RuntimeException(); class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1)); } public void onBehaviourHeader(JavaBehaviour jb) throws java.io.IOException { output.write(jb.getLiteral()); } public void onAttributeHeader(JavaAttribute ja) { } public void onClassFeature(final JavaFeature jf, final String docComment) throws IOException, InjectorParseException { //System.out.println("onClassFeature("+jf.getName()+" "+docComment+")"); if(!class_state.isInterface()) { if(jf instanceof JavaAttribute && Modifier.isFinal(jf.getModifiers()) && Modifier.isStatic(jf.getModifiers()) && !discardnextfeature && containsTag(docComment, PERSISTENT_ATTRIBUTE)) { final String type = jf.getType(); final String persistentType; if("IntegerAttribute".equals(type)) persistentType = "Integer"; else if("StringAttribute".equals(type)) persistentType = "String"; else if("ItemAttribute".equals(type)) { persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE); } else throw new RuntimeException(); final JavaAttribute ja = (JavaAttribute)jf; ja.makePersistent(persistentType); if(containsTag(docComment, UNIQUE_ATTRIBUTE)) ja.makeUnique(); if(containsTag(docComment, READ_ONLY_ATTRIBUTE)) ja.makeReadOnly(); final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER); if(qualifier!=null) ja.makeQualified(Collections.singletonList(qualifier)); } } discardnextfeature=false; } public boolean onDocComment(String docComment) throws IOException { //System.out.println("onDocComment("+docComment+")"); if(containsTag(docComment, GENERATED)) { discardnextfeature=true; return false; } else { output.write(docComment); return true; } } public void onFileDocComment(String docComment) throws IOException { //System.out.println("onFileDocComment("+docComment+")"); output.write(docComment); if (class_state != null) { // handle doccomment immediately handleClassComment(class_state, docComment); } else { // remember to be handled as soon as we know what class we're talking about lastFileDocComment = docComment; } } public void onFileEnd() { if(!class_state_stack.isEmpty()) throw new RuntimeException(); } private static final boolean containsTag(final String docComment, final String tagName) { return docComment!=null && docComment.indexOf('@'+tagName)>=0 ; } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final Writer output, final JavaAttribute attribute) throws IOException { output.write("\t\treturn ("); output.write(attribute.getPersistentType()); output.write(")getAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(");"); output.write(lineSeparator); } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final Writer output, final JavaAttribute attribute) throws IOException { if(!attribute.isUnique()) { output.write("\t\ttry"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write('\t'); } output.write("\t\tsetAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(','); output.write(attribute.getName()); output.write(");"); output.write(lineSeparator); if(!attribute.isUnique()) { output.write("\t\t}"); output.write(lineSeparator); output.write("\t\tcatch("+UniqueViolationException.class.getName()+" e)"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);"); output.write(lineSeparator); output.write("\t\t}"); output.write(lineSeparator); } } }
package com.lothrazar.cyclicmagic.util; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public class UtilItemStack { /** * match item, damage, and NBT * * @param chestItem * @param bagItem * @return */ public static boolean canMerge(ItemStack chestItem, ItemStack bagItem) { if (chestItem.isEmpty() || bagItem.isEmpty()) { return false; } return (bagItem.getItem().equals(chestItem.getItem()) && bagItem.getItemDamage() == chestItem.getItemDamage() && ItemStack.areItemStackTagsEqual(bagItem, chestItem)); } public static int mergeItemsBetweenStacks(ItemStack takeFrom, ItemStack moveTo) { int room = moveTo.getMaxStackSize() - moveTo.getCount(); int moveover = 0; if (room > 0) { moveover = Math.min(takeFrom.getCount(), room); // moveTo.stackSize += moveover; // takeFrom.stackSize -= moveover; moveTo.grow(moveover); takeFrom.shrink(moveover); } return moveover; } public static int getMaxDmgFraction(Item tool, int d) { return tool.getMaxDamage() - (int) MathHelper.floor(tool.getMaxDamage() / d); } public static void damageItem(EntityLivingBase p, ItemStack s) { if (p instanceof EntityPlayer) { damageItem((EntityPlayer) p, s); } else { s.damageItem(1, p); } } public static void damageItem(EntityPlayer p, ItemStack s) { if (p.capabilities.isCreativeMode == false) { s.damageItem(1, p); } } public static String getRawName(Item item) { return item.getUnlocalizedName().replaceAll("item.", ""); } /** * Created becuase getStateFromMeta is deprecated, and its used everywhere so * tons of warnings, and i have no idea how simple/complex the solution will * be * * @param b * @param meta * @return */ @SuppressWarnings("deprecation") public static IBlockState getStateFromMeta(Block b, int meta) { return b.getStateFromMeta(meta); } /** * created to wrap up deprecated calls * * @param b * @param state * @param player * @param worldIn * @param pos * @return */ @SuppressWarnings("deprecation") public static float getPlayerRelativeBlockHardness(Block b, IBlockState state, EntityPlayer player, World worldIn, BlockPos pos) { return b.getPlayerRelativeBlockHardness(state, player, worldIn, pos); } @SuppressWarnings("deprecation") public static float getBlockHardness(IBlockState state, World worldIn, BlockPos pos) { //no way the forge hooks one has a stupid thing where <0 returns 0 return state.getBlock().getBlockHardness(state, worldIn, pos); // return b.getPlayerRelativeBlockHardness(state, player, worldIn, pos); } public static EntityItem dropItemStackInWorld(World worldObj, BlockPos pos, Block block) { return dropItemStackInWorld(worldObj, pos, new ItemStack(block)); } public static EntityItem dropItemStackInWorld(World worldObj, BlockPos pos, Item item) { return dropItemStackInWorld(worldObj, pos, new ItemStack(item)); } public static EntityItem dropItemStackInWorld(World worldObj, BlockPos pos, ItemStack stack) { EntityItem entityItem = new EntityItem(worldObj, pos.getX()+0.5D, pos.getY()+0.5D, pos.getZ()+0.5D, stack); if (worldObj.isRemote == false) { // do not spawn a second 'ghost' one onclient side worldObj.spawnEntity(entityItem); } return entityItem; } public static void dropItemStacksInWorld(World world, BlockPos pos, List<ItemStack> stacks) { for (ItemStack s : stacks) { UtilItemStack.dropItemStackInWorld(world, pos, s); } } public static boolean isEmpty(ItemStack is) { return is == null || is.isEmpty() || is == ItemStack.EMPTY; } public static String getStringForItemStack(ItemStack itemStack) { Item item = itemStack.getItem(); return item.getRegistryName().getResourceDomain() + ":" + item.getRegistryName().getResourcePath() + "/" + itemStack.getMetadata(); } public static String getStringForItem(Item item) { return item.getRegistryName().getResourceDomain() + ":" + item.getRegistryName().getResourcePath(); } public static String getStringForBlock(Block b) { return b.getRegistryName().getResourceDomain() + ":" + b.getRegistryName().getResourcePath(); } }
package com.mingzuozhibi.modules.disc; import com.mingzuozhibi.commons.base.BaseKeys.Name; import com.mingzuozhibi.commons.base.PageController; import com.mingzuozhibi.commons.logger.LoggerBind; import com.mingzuozhibi.modules.disc.Disc.DiscType; import com.mingzuozhibi.modules.record.RecordService; import com.mingzuozhibi.modules.spider.HistoryRepository; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import javax.persistence.criteria.Predicate; import java.time.Instant; import java.time.LocalDate; import java.util.*; import static com.mingzuozhibi.commons.utils.MyTimeUtils.fmtDate; import static com.mingzuozhibi.modules.disc.DiscUtils.updateRank; import static com.mingzuozhibi.support.ChecksUtils.*; import static com.mingzuozhibi.support.ModifyUtils.*; @Transactional @RestController @LoggerBind(Name.SERVER_USER) public class DiscController extends PageController { @Autowired private RecordService recordService; @Autowired private DiscRepository discRepository; @Autowired private HistoryRepository historyRepository; @GetMapping(value = "/api/discs", produces = MEDIA_TYPE) public String findAll(@RequestParam(required = false) String title, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "20") int size) { var discs = discRepository.findAll((Specification<Disc>) (root, query, cb) -> { List<Predicate> predicates = new LinkedList<>(); if (title != null) { Arrays.stream(title.trim().split("\\s+")).forEach(text -> { predicates.add(cb.or( cb.like(root.get("title"), "%" + text.trim() + "%"), cb.like(root.get("titlePc"), "%" + text.trim() + "%") )); }); } return query.where(predicates.toArray(Predicate[]::new)).getRestriction(); }, PageRequest.of(page - 1, size)); return pageResult(discs.map(Disc::toJson)); } @GetMapping(value = "/api/discs/{id}", produces = MEDIA_TYPE) public String findById(@PathVariable Long id) { var byId = discRepository.findById(id); if (byId.isEmpty()) { return paramNotExists("ID"); } return dataResult(byId.get().toJson()); } @GetMapping(value = "/api/discs/asin/{asin}", produces = MEDIA_TYPE) public String findByAsin(@PathVariable String asin) { var byAsin = discRepository.findByAsin(asin); if (byAsin.isEmpty()) { return paramNotExists("ASIN"); } return dataResult(byAsin.get().toJson()); } @GetMapping(value = "/api/discs/{id}/records", produces = MEDIA_TYPE) public String findRecords(@PathVariable Long id) { var byId = discRepository.findById(id); if (byId.isEmpty()) { return paramNotExists("ID"); } var disc = byId.get(); var object = gson.toJsonTree(disc).getAsJsonObject(); object.add("records", recordService.buildDiscRecords(disc)); return dataResult(object); } @Setter private static class CreateForm { private String asin; private String title; private DiscType discType; private String releaseDate; } @PreAuthorize("hasRole('BASIC')") @PostMapping(value = "/api/discs", produces = MEDIA_TYPE) public String doCreate(@RequestBody CreateForm form) { var checks = runChecks( checkNotEmpty(form.asin, "ASIN"), checkStrMatch(form.asin, "ASIN", "[A-Z0-9]{10}"), checkNotEmpty(form.discType, ""), checkNotEmpty(form.releaseDate, ""), checkStrMatch(form.releaseDate, "", "\\d{4}/\\d{1,2}/\\d{1,2}") ); if (checks.isPresent()) { return errorResult(checks.get()); } if (StringUtils.isEmpty(form.title)) { form.title = form.asin; } if (discRepository.existsByAsin(form.asin)) { return paramExists("ASIN"); } var localDate = LocalDate.parse(form.releaseDate, fmtDate); var disc = new Disc(form.asin, form.title, form.discType, localDate); discRepository.save(disc); historyRepository.setTracked(form.asin, true); bind.success(logCreate("()", disc.getLogName(), disc.toJson().toString())); return dataResult(disc.toJson()); } @Setter private static class UpdateForm { private String titlePc; private DiscType discType; private String releaseDate; } @PreAuthorize("hasRole('BASIC')") @PutMapping(value = "/api/discs/{id}", produces = MEDIA_TYPE) public String doUpdate(@PathVariable Long id, @RequestBody UpdateForm form) { var checks = runChecks( checkNotEmpty(form.discType, ""), checkNotEmpty(form.releaseDate, ""), checkStrMatch(form.releaseDate, "", "\\d{4}/\\d{1,2}/\\d{1,2}") ); if (checks.isPresent()) { return errorResult(checks.get()); } var localDate = LocalDate.parse(form.releaseDate, fmtDate); var byId = discRepository.findById(id); if (byId.isEmpty()) { return paramNotExists("ID"); } var disc = byId.get(); if (!Objects.equals(disc.getTitlePc(), form.titlePc)) { bind.info(logUpdate("", disc.getTitlePc(), form.titlePc, disc.getLogName())); disc.setTitlePc(form.titlePc); } if (!Objects.equals(disc.getDiscType(), form.discType)) { bind.notify(logUpdate("", disc.getDiscType(), form.discType, disc.getLogName())); disc.setDiscType(form.discType); } if (!Objects.equals(disc.getReleaseDate(), localDate)) { bind.notify(logUpdate("", disc.getReleaseDate(), localDate, disc.getLogName())); disc.setReleaseDate(localDate); } return dataResult(disc.toJson()); } @Setter private static class PatchForm { Integer rank; } @PreAuthorize("hasRole('BASIC')") @PatchMapping(value = "/api/discs/{id}", produces = MEDIA_TYPE) public String doPatch(@PathVariable Long id, @RequestBody PatchForm form) { var byId = discRepository.findById(id); if (byId.isEmpty()) { return paramNotExists("ID"); } var disc = byId.get(); if (form.rank != null && !(Objects.equals(form.rank, disc.getThisRank()))) { updateRank(disc, form.rank, Instant.now()); amqpSender.bind(Name.DEFAULT).debug(logUpdate("", disc.getPrevRank(), disc.getThisRank(), disc.getLogName())); } return dataResult(disc.toJson()); } }
package com.mixpanel.android.mpmetrics; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; // Will be called from both customer threads and the Mixpanel worker thread. // States and behavior // - Set callback, and one is already cached in memory // - Call back with cached // - Set callback, waiting callback, running request is ancient // - Call waiting callback with null // - set waiting callback // - start request // - Set callback, waiting callback // - Call back with null // - Set callback, running request is ancient // - Set waiting callback // - Start request // - Set callback, running request is young // - Set waiting callback // - Set callback, recent request // - Call back with null // - Set callback // - Set waiting callback // - start request // - Call back from request // - Fill cache // - Serve waiting callbacks from cache // - Clear waiting callbacks /* package */ class DecideUpdates { public DecideUpdates(String token) { mToken = token; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); resetState(null); } public synchronized void setSurveyCallback(SurveyCallbacks callbacks, final String distinctId, final AnalyticsMessages messages) { if (! distinctId.equals(mRequestDistinctId)) { resetState(distinctId); // Purge all state if we have a new distinctId } long lastRequestAge = 1 + MPConfig.DECIDE_REQUEST_TIMEOUT_MILLIS; if (mRequestRunningSince >= 0) { lastRequestAge = currentTimeMillis() - mRequestRunningSince; } final boolean runningRequestIsAncient = mRequestIsRunning && lastRequestAge > MPConfig.DECIDE_REQUEST_TIMEOUT_MILLIS; final boolean lastRequestIsRecent = lastRequestAge < MPConfig.MAX_DECIDE_REQUEST_FREQUENCY_MILLIS; final Survey cached = popSurvey(); if (cached != null) { runSurveyCallback(cached, callbacks); } else if (null != mWaitingSurveyCallbacks && runningRequestIsAncient) { runSurveyCallback(null, mWaitingSurveyCallbacks); mWaitingSurveyCallbacks = callbacks; requestDecideCheck(distinctId, messages); } else if (null != mWaitingSurveyCallbacks) { runSurveyCallback(null, callbacks); } else if (runningRequestIsAncient) { mWaitingSurveyCallbacks = callbacks; requestDecideCheck(distinctId, messages); } else if (mRequestIsRunning) { mWaitingSurveyCallbacks = callbacks; } else if (lastRequestIsRecent) { runSurveyCallback(null, callbacks); } else { mWaitingSurveyCallbacks = callbacks; requestDecideCheck(distinctId, messages); } } public synchronized void setInAppCallback(InAppNotificationCallbacks callbacks, final String distinctId, final AnalyticsMessages messages) { if (! distinctId.equals(mRequestDistinctId)) { resetState(distinctId); // Purge all state if we have a new distinctId } long lastRequestAge = 1 + MPConfig.DECIDE_REQUEST_TIMEOUT_MILLIS; if (mRequestRunningSince >= 0) { lastRequestAge = currentTimeMillis() - mRequestRunningSince; } final boolean runningRequestIsAncient = mRequestIsRunning && lastRequestAge > MPConfig.DECIDE_REQUEST_TIMEOUT_MILLIS; final boolean lastRequestIsRecent = lastRequestAge < MPConfig.MAX_DECIDE_REQUEST_FREQUENCY_MILLIS; final InAppNotification cached = popNotification(); if (cached != null) { runInAppCallback(cached, callbacks); } else if (null != mWaitingInAppCallbacks && runningRequestIsAncient) { runInAppCallback(null, mWaitingInAppCallbacks); mWaitingInAppCallbacks = callbacks; requestDecideCheck(distinctId, messages); } else if (null != mWaitingInAppCallbacks) { runInAppCallback(null, callbacks); } else if (runningRequestIsAncient) { mWaitingInAppCallbacks = callbacks; requestDecideCheck(distinctId, messages); } else if (mRequestIsRunning) { mWaitingInAppCallbacks = callbacks; } else if (lastRequestIsRecent) { runInAppCallback(null, callbacks); } else { mWaitingInAppCallbacks = callbacks; requestDecideCheck(distinctId, messages); } } /* package */ synchronized void reportResults(String distinctId, List<Survey> newSurveys, List<InAppNotification> newNotifications) { if (! distinctId.equals(mRequestDistinctId)) { // Stale request, ignore it Log.i(LOGTAG, "Received decide results for an old distinct id, discarding them."); return; } mRequestIsRunning = false; for (final Survey s: newSurveys) { final int id = s.getId(); if (! mSurveyIds.contains(id)) { mSurveyIds.add(id); mUnseenSurveys.add(s); } } for (final InAppNotification n: newNotifications) { final int id = n.getId(); if (! mNotificationIds.contains(id)) { mNotificationIds.add(id); mUnseenNotifications.add(n); } } if (null != mWaitingSurveyCallbacks) { final Survey survey = popSurvey(); runSurveyCallback(survey, mWaitingSurveyCallbacks); mWaitingSurveyCallbacks = null; } if (null != mWaitingInAppCallbacks) { final InAppNotification notification = popNotification(); runInAppCallback(notification, mWaitingInAppCallbacks); mWaitingInAppCallbacks = null; } } /* package */ long currentTimeMillis() { return System.currentTimeMillis(); } // FOR TESTING ONLY. In the real app, this will be useless and race-condition-tacular /* package */ List<Survey> peekAtSurveyCache() { return mUnseenSurveys; } /* package */ List<InAppNotification> peekAtNotificationCache() { return mUnseenNotifications; } protected ServerMessage newPoster() { return new ServerMessage(); } private Survey popSurvey() { if (mUnseenSurveys.isEmpty()) { return null; } return mUnseenSurveys.remove(0); } private InAppNotification popNotification() { if (mUnseenNotifications.isEmpty()) { return null; } return mUnseenNotifications.remove(0); } private void requestDecideCheck(final String distinctId, final AnalyticsMessages messages) { mRequestRunningSince = currentTimeMillis(); mRequestIsRunning = true; mRequestDistinctId = distinctId; final DecideCallbacks callbacks = new DecideCallbacks() { @Override public void foundResults(List<Survey> surveys, List<InAppNotification> notifications) { reportResults(distinctId, surveys, notifications); } }; final DecideChecker.DecideCheck check = new DecideChecker.DecideCheck(callbacks, distinctId, mToken); messages.checkDecideService(check); } private void runSurveyCallback(final Survey survey, final SurveyCallbacks callbacks) { final Runnable task = new Runnable() { @Override public void run() { callbacks.foundSurvey(survey); } }; mWaitingSurveyCallbacks = null; runOnIsolatedThread(task); } private void runInAppCallback(final InAppNotification tryNotification, final InAppNotificationCallbacks callbacks) { final Runnable task = new Runnable() { @Override public void run() { InAppNotification reportNotification = null; try { if (null != tryNotification) { String imageUrl; if (tryNotification.getType() == InAppNotification.Type.MINI) { imageUrl = tryNotification.getImageUrl(); } else { imageUrl = tryNotification.getImage2xUrl(); } final ServerMessage imageMessage = newPoster(); final ServerMessage.Result result = imageMessage.get(imageUrl, null); if (result.getStatus() != ServerMessage.Status.SUCCEEDED) { // Shouldn't drop this notification on the floor if this is a connectivity issue! Log.i(LOGTAG, "Could not access image at " + imageUrl); } else { final byte[] imageBytes = result.getResponseBytes(); final Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); if (null == image) { Log.w(LOGTAG, "Notification referred to bad or corrupted image at " + imageUrl); } else { tryNotification.setImage(image); reportNotification = tryNotification; } } } } catch (OutOfMemoryError e) { Log.w(LOGTAG, "Notification image is too big, can't fit it into memory.", e); } callbacks.foundNotification(reportNotification); } }; runOnIsolatedThread(task); } // Protected for TESTING ONLY. DO NOT OVERRIDE outside of tests. protected void runOnIsolatedThread(Runnable task) { // 1) this gets called from multiple threads (possibly the Mixpanel processing thread) // 2) It ends up running arbitrary customer code that could take a long time // or flame out. if (Build.VERSION.SDK_INT >= 11) { AsyncTask.execute(task); } else { final Thread callbackThread = new Thread(task); callbackThread.run(); } } private void resetState(String distinctId) { mSurveyIds.clear(); mNotificationIds.clear(); mUnseenSurveys.clear(); mUnseenNotifications.clear(); if (null != mWaitingSurveyCallbacks) { runSurveyCallback(null, mWaitingSurveyCallbacks); } mWaitingSurveyCallbacks = null; if (null != mWaitingInAppCallbacks) { runInAppCallback(null, mWaitingInAppCallbacks); } mWaitingInAppCallbacks = null; mRequestIsRunning = false; mRequestRunningSince = -1; mRequestDistinctId = distinctId; } private final String mToken; private final Set<Integer> mSurveyIds; private final Set<Integer> mNotificationIds; // STATES private final List<Survey> mUnseenSurveys; private final List<InAppNotification> mUnseenNotifications; private SurveyCallbacks mWaitingSurveyCallbacks; private InAppNotificationCallbacks mWaitingInAppCallbacks; private boolean mRequestIsRunning; private long mRequestRunningSince; private String mRequestDistinctId; private static final String LOGTAG = "MixpanelAPI DecideUpdates"; }
package com.mixpanel.android.viewcrawler; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.Process; import android.util.JsonWriter; import android.util.Pair; import com.mixpanel.android.mpmetrics.MPConfig; import com.mixpanel.android.mpmetrics.MixpanelAPI; import com.mixpanel.android.mpmetrics.OnMixpanelTweaksUpdatedListener; import com.mixpanel.android.mpmetrics.ResourceIds; import com.mixpanel.android.mpmetrics.ResourceReader; import com.mixpanel.android.mpmetrics.SuperPropertyUpdate; import com.mixpanel.android.mpmetrics.Tweaks; import com.mixpanel.android.util.ImageStore; import com.mixpanel.android.util.JSONUtils; import com.mixpanel.android.util.MPLog; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.net.ssl.SSLSocketFactory; /** * This class is for internal use by the Mixpanel API, and should * not be called directly by your code. */ @TargetApi(MPConfig.UI_FEATURES_MIN_API) public class ViewCrawler implements UpdatesFromMixpanel, TrackingDebug, ViewVisitor.OnLayoutErrorListener { public ViewCrawler(Context context, String token, MixpanelAPI mixpanel, Tweaks tweaks) { mConfig = MPConfig.getInstance(context); mContext = context; mEditState = new EditState(); mTweaks = tweaks; mDeviceInfo = mixpanel.getDeviceInfo(); mScaledDensity = Resources.getSystem().getDisplayMetrics().scaledDensity; mTweaksUpdatedListeners = Collections.newSetFromMap(new ConcurrentHashMap<OnMixpanelTweaksUpdatedListener, Boolean>()); final HandlerThread thread = new HandlerThread(ViewCrawler.class.getCanonicalName()); thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mMessageThreadHandler = new ViewCrawlerHandler(context, token, thread.getLooper(), this); mDynamicEventTracker = new DynamicEventTracker(mixpanel, mMessageThreadHandler); mMixpanel = mixpanel; final Application app = (Application) context.getApplicationContext(); app.registerActivityLifecycleCallbacks(new LifecycleCallbacks()); mTweaks.addOnTweakDeclaredListener(new Tweaks.OnTweakDeclaredListener() { @Override public void onTweakDeclared() { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_DEVICE_INFO); mMessageThreadHandler.sendMessage(msg); } }); } @Override public void startUpdates() { mMessageThreadHandler.start(); mMessageThreadHandler.sendMessage(mMessageThreadHandler.obtainMessage(MESSAGE_INITIALIZE_CHANGES)); } @Override public Tweaks getTweaks() { return mTweaks; } @Override public void setEventBindings(JSONArray bindings) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_EVENT_BINDINGS_RECEIVED); msg.obj = bindings; mMessageThreadHandler.sendMessage(msg); } @Override public void setVariants(JSONArray variants) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_VARIANTS_RECEIVED); msg.obj = variants; mMessageThreadHandler.sendMessage(msg); } @Override public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { if (null == listener) { throw new NullPointerException("Listener cannot be null"); } mTweaksUpdatedListeners.add(listener); } @Override public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { mTweaksUpdatedListeners.remove(listener); } @Override public void reportTrack(String eventName) { final Message m = mMessageThreadHandler.obtainMessage(); m.what = MESSAGE_SEND_EVENT_TRACKED; m.obj = eventName; mMessageThreadHandler.sendMessage(m); } @Override public void onLayoutError(ViewVisitor.LayoutErrorMessage e) { final Message m = mMessageThreadHandler.obtainMessage(); m.what = MESSAGE_SEND_LAYOUT_ERROR; m.obj = e; mMessageThreadHandler.sendMessage(m); } private class EmulatorConnector implements Runnable { public EmulatorConnector() { mStopped = true; } @Override public void run() { if (! mStopped) { final Message message = mMessageThreadHandler.obtainMessage(MESSAGE_CONNECT_TO_EDITOR); mMessageThreadHandler.sendMessage(message); } mMessageThreadHandler.postDelayed(this, EMULATOR_CONNECT_ATTEMPT_INTERVAL_MILLIS); } public void start() { mStopped = false; mMessageThreadHandler.post(this); } public void stop() { mStopped = true; mMessageThreadHandler.removeCallbacks(this); } private volatile boolean mStopped; } private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks, FlipGesture.OnFlipGestureListener { public LifecycleCallbacks() { mFlipGesture = new FlipGesture(this); mEmulatorConnector = new EmulatorConnector(); } @Override public void onFlipGesture() { mMixpanel.track("$ab_gesture3"); final Message message = mMessageThreadHandler.obtainMessage(MESSAGE_CONNECT_TO_EDITOR); mMessageThreadHandler.sendMessage(message); } @Override public void onActivityCreated(Activity activity, Bundle bundle) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { installConnectionSensor(activity); mEditState.add(activity); } @Override public void onActivityPaused(Activity activity) { mEditState.remove(activity); uninstallConnectionSensor(activity); } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { } private void installConnectionSensor(final Activity activity) { if (isInEmulator() && !mConfig.getDisableEmulatorBindingUI()) { mEmulatorConnector.start(); } else if (!mConfig.getDisableGestureBindingUI()) { final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); final Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(mFlipGesture, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); } } private void uninstallConnectionSensor(final Activity activity) { if (isInEmulator() && !mConfig.getDisableEmulatorBindingUI()) { mEmulatorConnector.stop(); } else if (!mConfig.getDisableGestureBindingUI()) { final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); sensorManager.unregisterListener(mFlipGesture); } } private boolean isInEmulator() { if (!Build.HARDWARE.equals("goldfish") && !Build.HARDWARE.equals("ranchu")) { return false; } if (!Build.BRAND.startsWith("generic") && !Build.BRAND.equals("Android")) { return false; } if (!Build.DEVICE.startsWith("generic")) { return false; } if (!Build.PRODUCT.contains("sdk")) { return false; } if (!Build.MODEL.toLowerCase(Locale.US).contains("sdk")) { return false; } return true; } private final FlipGesture mFlipGesture; private final EmulatorConnector mEmulatorConnector; } private class ViewCrawlerHandler extends Handler { public ViewCrawlerHandler(Context context, String token, Looper looper, ViewVisitor.OnLayoutErrorListener layoutErrorListener) { super(looper); mToken = token; mSnapshot = null; String resourcePackage = mConfig.getResourcePackageName(); if (null == resourcePackage) { resourcePackage = context.getPackageName(); } final ResourceIds resourceIds = new ResourceReader.Ids(resourcePackage, context); mImageStore = new ImageStore(context, "ViewCrawler"); mProtocol = new EditProtocol(context, resourceIds, mImageStore, layoutErrorListener); mEditorChanges = new HashMap<String, Pair<String, JSONObject>>(); mEditorTweaks = new ArrayList<JSONObject>(); mEditorAssetUrls = new ArrayList<String>(); mEditorEventBindings = new ArrayList<Pair<String, JSONObject>>(); mPersistentChanges = new ArrayList<VariantChange>(); mPersistentTweaks = new ArrayList<VariantTweak>(); mPersistentEventBindings = new ArrayList<Pair<String, JSONObject>>(); mSeenExperiments = new HashSet<Pair<Integer, Integer>>(); mStartLock = new ReentrantLock(); mStartLock.lock(); } public void start() { mStartLock.unlock(); } @Override public void handleMessage(Message msg) { mStartLock.lock(); try { final int what = msg.what; switch (what) { case MESSAGE_INITIALIZE_CHANGES: loadKnownChanges(); initializeChanges(); break; case MESSAGE_CONNECT_TO_EDITOR: connectToEditor(); break; case MESSAGE_SEND_DEVICE_INFO: sendDeviceInfo(); break; case MESSAGE_SEND_STATE_FOR_EDITING: sendSnapshot((JSONObject) msg.obj); break; case MESSAGE_SEND_EVENT_TRACKED: sendReportTrackToEditor((String) msg.obj); break; case MESSAGE_SEND_LAYOUT_ERROR: sendLayoutError((ViewVisitor.LayoutErrorMessage) msg.obj); break; case MESSAGE_VARIANTS_RECEIVED: handleVariantsReceived((JSONArray) msg.obj); break; case MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED: handleEditorChangeReceived((JSONObject) msg.obj); break; case MESSAGE_EVENT_BINDINGS_RECEIVED: handleEventBindingsReceived((JSONArray) msg.obj); break; case MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED: handleEditorBindingsReceived((JSONObject) msg.obj); break; case MESSAGE_HANDLE_EDITOR_CHANGES_CLEARED: handleEditorBindingsCleared((JSONObject) msg.obj); break; case MESSAGE_HANDLE_EDITOR_TWEAKS_RECEIVED: handleEditorTweaksReceived((JSONObject) msg.obj); break; case MESSAGE_HANDLE_EDITOR_CLOSED: handleEditorClosed(); break; } } finally { mStartLock.unlock(); } } /** * Load the experiment ids and variants already in persistent storage into * into our set of seen experiments, so we don't double track them. */ private void loadKnownChanges() { final SharedPreferences preferences = getSharedPreferences(); final String storedChanges = preferences.getString(SHARED_PREF_CHANGES_KEY, null); if (null != storedChanges) { try { final JSONArray variants = new JSONArray(storedChanges); final int variantsLength = variants.length(); for (int i = 0; i < variantsLength; i++) { final JSONObject variant = variants.getJSONObject(i); final int variantId = variant.getInt("id"); final int experimentId = variant.getInt("experiment_id"); final Pair<Integer,Integer> sight = new Pair<Integer,Integer>(experimentId, variantId); mSeenExperiments.add(sight); } } catch (JSONException e) { MPLog.e(LOGTAG, "Malformed variants found in persistent storage, clearing all variants", e); final SharedPreferences.Editor editor = preferences.edit(); editor.remove(SHARED_PREF_CHANGES_KEY); editor.remove(SHARED_PREF_BINDINGS_KEY); editor.apply(); } } } /** * Load stored changes from persistent storage and apply them to the application. */ private void initializeChanges() { final SharedPreferences preferences = getSharedPreferences(); final String storedChanges = preferences.getString(SHARED_PREF_CHANGES_KEY, null); final String storedBindings = preferences.getString(SHARED_PREF_BINDINGS_KEY, null); List<Pair<Integer, Integer>> emptyVariantIds = new ArrayList<>(); try { mPersistentChanges.clear(); mPersistentTweaks.clear(); if (null != storedChanges) { final JSONArray variants = new JSONArray(storedChanges); final int variantsLength = variants.length(); for (int variantIx = 0; variantIx < variantsLength; variantIx++) { final JSONObject nextVariant = variants.getJSONObject(variantIx); final int variantIdPart = nextVariant.getInt("id"); final int experimentIdPart = nextVariant.getInt("experiment_id"); final Pair<Integer, Integer> variantId = new Pair<Integer, Integer>(experimentIdPart, variantIdPart); final JSONArray actions = nextVariant.getJSONArray("actions"); final int actionsLength = actions.length(); for (int i = 0; i < actionsLength; i++) { final JSONObject change = actions.getJSONObject(i); final String targetActivity = JSONUtils.optionalStringKey(change, "target_activity"); final VariantChange variantChange = new VariantChange(targetActivity, change, variantId); mPersistentChanges.add(variantChange); } final JSONArray tweaks = nextVariant.getJSONArray("tweaks"); final int tweaksLength = tweaks.length(); for (int i = 0; i < tweaksLength; i++) { final JSONObject tweakDesc = tweaks.getJSONObject(i); final VariantTweak variantTweak = new VariantTweak(tweakDesc, variantId); mPersistentTweaks.add(variantTweak); } if (actionsLength == 0 && tweaksLength == 0) { final Pair<Integer, Integer> emptyVariantId = new Pair<Integer, Integer>(experimentIdPart, variantIdPart); emptyVariantIds.add(emptyVariantId); } } } if (null != storedBindings) { final JSONArray bindings = new JSONArray(storedBindings); mPersistentEventBindings.clear(); for (int i = 0; i < bindings.length(); i++) { final JSONObject event = bindings.getJSONObject(i); final String targetActivity = JSONUtils.optionalStringKey(event, "target_activity"); mPersistentEventBindings.add(new Pair<String, JSONObject>(targetActivity, event)); } } } catch (final JSONException e) { MPLog.i(LOGTAG, "JSON error when initializing saved changes, clearing persistent memory", e); final SharedPreferences.Editor editor = preferences.edit(); editor.remove(SHARED_PREF_CHANGES_KEY); editor.remove(SHARED_PREF_BINDINGS_KEY); editor.apply(); } applyVariantsAndEventBindings(emptyVariantIds); } /** * Try to connect to the remote interactive editor, if a connection does not already exist. */ private void connectToEditor() { MPLog.v(LOGTAG, "connecting to editor"); if (mEditorConnection != null && mEditorConnection.isValid()) { MPLog.v(LOGTAG, "There is already a valid connection to an events editor."); return; } final SSLSocketFactory socketFactory = mConfig.getSSLSocketFactory(); if (null == socketFactory) { MPLog.v(LOGTAG, "SSL is not available on this device, no connection will be attempted to the events editor."); return; } final String url = MPConfig.getInstance(mContext).getEditorUrl() + mToken; try { final Socket sslSocket = socketFactory.createSocket(); mEditorConnection = new EditorConnection(new URI(url), new Editor(), sslSocket); } catch (final URISyntaxException e) { MPLog.e(LOGTAG, "Error parsing URI " + url + " for editor websocket", e); } catch (final EditorConnection.EditorConnectionException e) { MPLog.e(LOGTAG, "Error connecting to URI " + url, e); } catch (final IOException e) { MPLog.i(LOGTAG, "Can't create SSL Socket to connect to editor service", e); } } /** * Send a string error message to the connected web UI. */ private void sendError(String errorMessage) { if (mEditorConnection == null || !mEditorConnection.isValid()) { return; } final JSONObject errorObject = new JSONObject(); try { errorObject.put("error_message", errorMessage); } catch (final JSONException e) { MPLog.e(LOGTAG, "Apparently impossible JSONException", e); } final OutputStreamWriter writer = new OutputStreamWriter(mEditorConnection.getBufferedOutputStream()); try { writer.write("{\"type\": \"error\", "); writer.write("\"payload\": "); writer.write(errorObject.toString()); writer.write("}"); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't write error message to editor", e); } finally { try { writer.close(); } catch (final IOException e) { MPLog.e(LOGTAG, "Could not close output writer to editor", e); } } } /** * Report on device info to the connected web UI. */ private void sendDeviceInfo() { if (mEditorConnection == null || !mEditorConnection.isValid()) { return; } final OutputStream out = mEditorConnection.getBufferedOutputStream(); final JsonWriter j = new JsonWriter(new OutputStreamWriter(out)); try { j.beginObject(); j.name("type").value("device_info_response"); j.name("payload").beginObject(); j.name("device_type").value("Android"); j.name("device_name").value(Build.BRAND + "/" + Build.MODEL); j.name("scaled_density").value(mScaledDensity); for (final Map.Entry<String, String> entry : mDeviceInfo.entrySet()) { j.name(entry.getKey()).value(entry.getValue()); } final Map<String, Tweaks.TweakValue> tweakDescs = mTweaks.getAllValues(); j.name("tweaks").beginArray(); for (Map.Entry<String, Tweaks.TweakValue> tweak:tweakDescs.entrySet()) { final Tweaks.TweakValue desc = tweak.getValue(); final String tweakName = tweak.getKey(); j.beginObject(); j.name("name").value(tweakName); j.name("minimum").value(desc.getMinimum()); j.name("maximum").value(desc.getMaximum()); switch (desc.type) { case Tweaks.BOOLEAN_TYPE: j.name("type").value("boolean"); j.name("value").value(desc.getBooleanValue()); break; case Tweaks.DOUBLE_TYPE: j.name("type").value("number"); j.name("encoding").value("d"); j.name("value").value(desc.getNumberValue().doubleValue()); break; case Tweaks.LONG_TYPE: j.name("type").value("number"); j.name("encoding").value("l"); j.name("value").value(desc.getNumberValue().longValue()); break; case Tweaks.STRING_TYPE: j.name("type").value("string"); j.name("value").value(desc.getStringValue()); break; default: MPLog.wtf(LOGTAG, "Unrecognized Tweak Type " + desc.type + " encountered."); } j.endObject(); } j.endArray(); j.endObject(); // payload j.endObject(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't write device_info to server", e); } finally { try { j.close(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't close websocket writer", e); } } } /** * Send a snapshot response, with crawled views and screenshot image, to the connected web UI. */ private void sendSnapshot(JSONObject message) { final long startSnapshot = System.currentTimeMillis(); try { final JSONObject payload = message.getJSONObject("payload"); if (payload.has("config")) { mSnapshot = mProtocol.readSnapshotConfig(payload); MPLog.v(LOGTAG, "Initializing snapshot with configuration"); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Payload with snapshot config required with snapshot request", e); sendError("Payload with snapshot config required with snapshot request"); return; } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Editor sent malformed message with snapshot request", e); sendError(e.getMessage()); return; } if (null == mSnapshot) { sendError("No snapshot configuration (or a malformed snapshot configuration) was sent."); MPLog.w(LOGTAG, "Mixpanel editor is misconfigured, sent a snapshot request without a valid configuration."); return; } // ELSE config is valid: final OutputStream out = mEditorConnection.getBufferedOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(out); try { writer.write("{"); writer.write("\"type\": \"snapshot_response\","); writer.write("\"payload\": {"); { writer.write("\"activities\":"); writer.flush(); mSnapshot.snapshots(mEditState, out); } final long snapshotTime = System.currentTimeMillis() - startSnapshot; writer.write(",\"snapshot_time_millis\": "); writer.write(Long.toString(snapshotTime)); writer.write("}"); // } payload writer.write("}"); // } whole message } catch (final IOException e) { MPLog.e(LOGTAG, "Can't write snapshot request to server", e); } finally { try { writer.close(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't close writer.", e); } } } /** * Report that a track has occurred to the connected web UI. */ private void sendReportTrackToEditor(String eventName) { if (mEditorConnection == null || !mEditorConnection.isValid()) { return; } final OutputStream out = mEditorConnection.getBufferedOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(out); final JsonWriter j = new JsonWriter(writer); try { j.beginObject(); j.name("type").value("track_message"); j.name("payload"); { j.beginObject(); j.name("event_name").value(eventName); j.endObject(); } j.endObject(); j.flush(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't write track_message to server", e); } finally { try { j.close(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't close writer.", e); } } } private void sendLayoutError(ViewVisitor.LayoutErrorMessage exception) { if (mEditorConnection == null ) { return; } final OutputStream out = mEditorConnection.getBufferedOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(out); final JsonWriter j = new JsonWriter(writer); try { j.beginObject(); j.name("type").value("layout_error"); j.name("exception_type").value(exception.getErrorType()); j.name("cid").value(exception.getName()); j.endObject(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't write track_message to server", e); } finally { try { j.close(); } catch (final IOException e) { MPLog.e(LOGTAG, "Can't close writer.", e); } } } /** * Accept and apply a change from the connected UI. */ private void handleEditorChangeReceived(JSONObject changeMessage) { try { final JSONObject payload = changeMessage.getJSONObject("payload"); final JSONArray actions = payload.getJSONArray("actions"); for (int i = 0; i < actions.length(); i++) { final JSONObject change = actions.getJSONObject(i); final String targetActivity = JSONUtils.optionalStringKey(change, "target_activity"); final String name = change.getString("name"); mEditorChanges.put(name, new Pair<String, JSONObject>(targetActivity, change)); } applyVariantsAndEventBindings(Collections.<Pair<Integer, Integer>>emptyList()); } catch (final JSONException e) { MPLog.e(LOGTAG, "Bad change request received", e); } } /** * Remove a change from the connected UI. */ private void handleEditorBindingsCleared(JSONObject clearMessage) { try { final JSONObject payload = clearMessage.getJSONObject("payload"); final JSONArray actions = payload.getJSONArray("actions"); // Don't throw any JSONExceptions after this, or you'll leak the item for (int i = 0; i < actions.length(); i++) { final String changeId = actions.getString(i); mEditorChanges.remove(changeId); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Bad clear request received", e); } applyVariantsAndEventBindings(Collections.<Pair<Integer, Integer>>emptyList()); } private void handleEditorTweaksReceived(JSONObject tweaksMessage) { try { mEditorTweaks.clear(); final JSONObject payload = tweaksMessage.getJSONObject("payload"); final JSONArray tweaks = payload.getJSONArray("tweaks"); final int length = tweaks.length(); for (int i = 0; i < length; i++) { final JSONObject tweakDesc = tweaks.getJSONObject(i); mEditorTweaks.add(tweakDesc); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Bad tweaks received", e); } applyVariantsAndEventBindings(Collections.<Pair<Integer, Integer>>emptyList()); } /** * Accept and apply variant changes from a non-interactive source. */ private void handleVariantsReceived(JSONArray variants) { final SharedPreferences preferences = getSharedPreferences(); final SharedPreferences.Editor editor = preferences.edit(); if(variants.length() > 0) { editor.putString(SHARED_PREF_CHANGES_KEY, variants.toString()); } else { editor.remove(SHARED_PREF_CHANGES_KEY); } editor.apply(); initializeChanges(); } /** * Accept and apply a persistent event binding from a non-interactive source. */ private void handleEventBindingsReceived(JSONArray eventBindings) { final SharedPreferences preferences = getSharedPreferences(); final SharedPreferences.Editor editor = preferences.edit(); editor.putString(SHARED_PREF_BINDINGS_KEY, eventBindings.toString()); editor.apply(); initializeChanges(); } /** * Accept and apply a temporary event binding from the connected UI. */ private void handleEditorBindingsReceived(JSONObject message) { final JSONArray eventBindings; try { final JSONObject payload = message.getJSONObject("payload"); eventBindings = payload.getJSONArray("events"); } catch (final JSONException e) { MPLog.e(LOGTAG, "Bad event bindings received", e); return; } final int eventCount = eventBindings.length(); mEditorEventBindings.clear(); for (int i = 0; i < eventCount; i++) { try { final JSONObject event = eventBindings.getJSONObject(i); final String targetActivity = JSONUtils.optionalStringKey(event, "target_activity"); mEditorEventBindings.add(new Pair<String, JSONObject>(targetActivity, event)); } catch (final JSONException e) { MPLog.e(LOGTAG, "Bad event binding received from editor in " + eventBindings.toString(), e); } } applyVariantsAndEventBindings(Collections.<Pair<Integer, Integer>>emptyList()); } /** * Clear state associated with the editor now that the editor is gone. */ private void handleEditorClosed() { mEditorChanges.clear(); mEditorEventBindings.clear(); // Free (or make available) snapshot memory mSnapshot = null; MPLog.v(LOGTAG, "Editor closed- freeing snapshot"); applyVariantsAndEventBindings(Collections.<Pair<Integer, Integer>>emptyList()); for (final String assetUrl:mEditorAssetUrls) { mImageStore.deleteStorage(assetUrl); } } /** * Reads our JSON-stored edits from memory and submits them to our EditState. Overwrites * any existing edits at the time that it is run. * * applyVariantsAndEventBindings should be called any time we load new edits, event bindings, * or tweaks from disk or when we receive new edits from the interactive UI editor. * Changes and event bindings from our persistent storage and temporary changes * received from interactive editing will all be submitted to our EditState, tweaks * will be updated, and experiment statuses will be tracked. */ private void applyVariantsAndEventBindings(List<Pair<Integer, Integer>> emptyVariantIds) { final List<Pair<String, ViewVisitor>> newVisitors = new ArrayList<Pair<String, ViewVisitor>>(); final Set<Pair<Integer, Integer>> toTrack = new HashSet<Pair<Integer, Integer>>(); { final int size = mPersistentChanges.size(); for (int i = 0; i < size; i++) { final VariantChange changeInfo = mPersistentChanges.get(i); try { final EditProtocol.Edit edit = mProtocol.readEdit(changeInfo.change); newVisitors.add(new Pair<String, ViewVisitor>(changeInfo.activityName, edit.visitor)); if (!mSeenExperiments.contains(changeInfo.variantId)) { toTrack.add(changeInfo.variantId); } } catch (final EditProtocol.CantGetEditAssetsException e) { MPLog.v(LOGTAG, "Can't load assets for an edit, won't apply the change now", e); } catch (final EditProtocol.InapplicableInstructionsException e) { MPLog.i(LOGTAG, e.getMessage()); } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Bad persistent change request cannot be applied.", e); } } } { boolean isTweaksUpdated = false; final int size = mPersistentTweaks.size(); for (int i = 0; i < size; i++) { final VariantTweak tweakInfo = mPersistentTweaks.get(i); try { final Pair<String, Object> tweakValue = mProtocol.readTweak(tweakInfo.tweak); if (!mSeenExperiments.contains(tweakInfo.variantId)) { toTrack.add(tweakInfo.variantId); isTweaksUpdated = true; } else if (mTweaks.isNewValue(tweakValue.first, tweakValue.second)) { isTweaksUpdated = true; } mTweaks.set(tweakValue.first, tweakValue.second); } catch (EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Bad editor tweak cannot be applied.", e); } } if (isTweaksUpdated) { for (OnMixpanelTweaksUpdatedListener listener : mTweaksUpdatedListeners) { listener.onMixpanelTweakUpdated(); } } if(size == 0) { // there are no new tweaks, so reset to default values final Map<String, Tweaks.TweakValue> tweakDefaults = mTweaks.getDefaultValues(); for (Map.Entry<String, Tweaks.TweakValue> tweak:tweakDefaults.entrySet()) { final Tweaks.TweakValue tweakValue = tweak.getValue(); final String tweakName = tweak.getKey(); mTweaks.set(tweakName, tweakValue); } } } { for (Pair<String, JSONObject> changeInfo:mEditorChanges.values()) { try { final EditProtocol.Edit edit = mProtocol.readEdit(changeInfo.second); newVisitors.add(new Pair<String, ViewVisitor>(changeInfo.first, edit.visitor)); mEditorAssetUrls.addAll(edit.imageUrls); } catch (final EditProtocol.CantGetEditAssetsException e) { MPLog.v(LOGTAG, "Can't load assets for an edit, won't apply the change now", e); } catch (final EditProtocol.InapplicableInstructionsException e) { MPLog.i(LOGTAG, e.getMessage()); } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Bad editor change request cannot be applied.", e); } } } { final int size = mEditorTweaks.size(); for (int i = 0; i < size; i++) { final JSONObject tweakDesc = mEditorTweaks.get(i); try { final Pair<String, Object> tweakValue = mProtocol.readTweak(tweakDesc); mTweaks.set(tweakValue.first, tweakValue.second); } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Strange tweaks received", e); } } } { final int size = mPersistentEventBindings.size(); for (int i = 0; i < size; i++) { final Pair<String, JSONObject> changeInfo = mPersistentEventBindings.get(i); try { final ViewVisitor visitor = mProtocol.readEventBinding(changeInfo.second, mDynamicEventTracker); newVisitors.add(new Pair<String, ViewVisitor>(changeInfo.first, visitor)); } catch (final EditProtocol.InapplicableInstructionsException e) { MPLog.i(LOGTAG, e.getMessage()); } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Bad persistent event binding cannot be applied.", e); } } } { final int size = mEditorEventBindings.size(); for (int i = 0; i < size; i++) { final Pair<String, JSONObject> changeInfo = mEditorEventBindings.get(i); try { final ViewVisitor visitor = mProtocol.readEventBinding(changeInfo.second, mDynamicEventTracker); newVisitors.add(new Pair<String, ViewVisitor>(changeInfo.first, visitor)); } catch (final EditProtocol.InapplicableInstructionsException e) { MPLog.i(LOGTAG, e.getMessage()); } catch (final EditProtocol.BadInstructionsException e) { MPLog.e(LOGTAG, "Bad editor event binding cannot be applied.", e); } } } final Map<String, List<ViewVisitor>> editMap = new HashMap<String, List<ViewVisitor>>(); final int totalEdits = newVisitors.size(); for (int i = 0; i < totalEdits; i++) { final Pair<String, ViewVisitor> next = newVisitors.get(i); final List<ViewVisitor> mapElement; if (editMap.containsKey(next.first)) { mapElement = editMap.get(next.first); } else { mapElement = new ArrayList<ViewVisitor>(); editMap.put(next.first, mapElement); } mapElement.add(next.second); } mEditState.setEdits(editMap); for (Pair<Integer, Integer> id : emptyVariantIds) { if (!mSeenExperiments.contains(id)) { toTrack.add(id); } } mSeenExperiments.addAll(toTrack); if (toTrack.size() > 0) { final JSONObject variantObject = new JSONObject(); try { for (Pair<Integer, Integer> variant : toTrack) { final int experimentId = variant.first; final int variantId = variant.second; final JSONObject trackProps = new JSONObject(); trackProps.put("$experiment_id", experimentId); trackProps.put("$variant_id", variantId); variantObject.put(Integer.toString(experimentId), variantId); mMixpanel.getPeople().merge("$experiments", variantObject); mMixpanel.updateSuperProperties(new SuperPropertyUpdate() { public JSONObject update(JSONObject in) { try { in.put("$experiments", variantObject); } catch (JSONException e) { MPLog.wtf(LOGTAG, "Can't write $experiments super property", e); } return in; } }); mMixpanel.track("$experiment_started", trackProps); } } catch (JSONException e) { MPLog.wtf(LOGTAG, "Could not build JSON for reporting experiment start", e); } } } private SharedPreferences getSharedPreferences() { final String sharedPrefsName = SHARED_PREF_EDITS_FILE + mToken; return mContext.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE); } private EditorConnection mEditorConnection; private ViewSnapshot mSnapshot; private final String mToken; private final Lock mStartLock; private final EditProtocol mProtocol; private final ImageStore mImageStore; private final Map<String, Pair<String,JSONObject>> mEditorChanges; private final List<JSONObject> mEditorTweaks; private final List<String> mEditorAssetUrls; private final List<Pair<String,JSONObject>> mEditorEventBindings; private final List<VariantChange> mPersistentChanges; private final List<VariantTweak> mPersistentTweaks; private final List<Pair<String,JSONObject>> mPersistentEventBindings; private final Set<Pair<Integer, Integer>> mSeenExperiments; } private class Editor implements EditorConnection.Editor { @Override public void sendSnapshot(JSONObject message) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_STATE_FOR_EDITING); msg.obj = message; mMessageThreadHandler.sendMessage(msg); } @Override public void performEdit(JSONObject message) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED); msg.obj = message; mMessageThreadHandler.sendMessage(msg); } @Override public void clearEdits(JSONObject message) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CHANGES_CLEARED); msg.obj = message; mMessageThreadHandler.sendMessage(msg); } @Override public void setTweaks(JSONObject message) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_TWEAKS_RECEIVED); msg.obj = message; mMessageThreadHandler.sendMessage(msg); } @Override public void bindEvents(JSONObject message) { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED); msg.obj = message; mMessageThreadHandler.sendMessage(msg); } @Override public void sendDeviceInfo() { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_DEVICE_INFO); mMessageThreadHandler.sendMessage(msg); } @Override public void cleanup() { final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CLOSED); mMessageThreadHandler.sendMessage(msg); } } private static class VariantChange { public VariantChange(String anActivityName, JSONObject someChange, Pair<Integer, Integer> aVariantId) { activityName = anActivityName; change = someChange; variantId = aVariantId; } public final String activityName; public final JSONObject change; public final Pair<Integer, Integer> variantId; } private static class VariantTweak { public VariantTweak(JSONObject aTweak, Pair<Integer, Integer> aVariantId) { tweak = aTweak; variantId = aVariantId; } public final JSONObject tweak; public final Pair<Integer, Integer> variantId; } private final MPConfig mConfig; private final Context mContext; private final MixpanelAPI mMixpanel; private final DynamicEventTracker mDynamicEventTracker; private final EditState mEditState; private final Tweaks mTweaks; private final Map<String, String> mDeviceInfo; private final ViewCrawlerHandler mMessageThreadHandler; private final float mScaledDensity; private final Set<OnMixpanelTweaksUpdatedListener> mTweaksUpdatedListeners; private static final String SHARED_PREF_EDITS_FILE = "mixpanel.viewcrawler.changes"; private static final String SHARED_PREF_CHANGES_KEY = "mixpanel.viewcrawler.changes"; private static final String SHARED_PREF_BINDINGS_KEY = "mixpanel.viewcrawler.bindings"; private static final int MESSAGE_INITIALIZE_CHANGES = 0; private static final int MESSAGE_CONNECT_TO_EDITOR = 1; private static final int MESSAGE_SEND_STATE_FOR_EDITING = 2; private static final int MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED = 3; private static final int MESSAGE_SEND_DEVICE_INFO = 4; private static final int MESSAGE_EVENT_BINDINGS_RECEIVED = 5; private static final int MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED = 6; private static final int MESSAGE_SEND_EVENT_TRACKED = 7; private static final int MESSAGE_HANDLE_EDITOR_CLOSED = 8; private static final int MESSAGE_VARIANTS_RECEIVED = 9; private static final int MESSAGE_HANDLE_EDITOR_CHANGES_CLEARED = 10; private static final int MESSAGE_HANDLE_EDITOR_TWEAKS_RECEIVED = 11; private static final int MESSAGE_SEND_LAYOUT_ERROR = 12; private static final int EMULATOR_CONNECT_ATTEMPT_INTERVAL_MILLIS = 1000 * 30; @SuppressWarnings("unused") private static final String LOGTAG = "MixpanelAPI.ViewCrawler"; }
package com.mixpanel.android.viewcrawler; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.ArrayMap; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.mixpanel.android.mpmetrics.MPConfig; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; @TargetApi(MPConfig.UI_FEATURES_MIN_API) /* package */ abstract class ViewVisitor implements Pathfinder.Accumulator { /** * OnEvent will be fired when whatever the ViewVisitor installed fires * (For example, if the ViewVisitor installs watches for clicks, then OnEvent will be called * on click) */ public interface OnEventListener { public void OnEvent(View host, String eventName, boolean debounce); } public interface OnLayoutErrorListener { public void onLayoutError(LayoutErrorMessage e); } public static class LayoutErrorMessage { public LayoutErrorMessage(String errorType, String name) { mErrorType = errorType; mName = name; } public String getErrorType() { return mErrorType; } public String getName() { return mName; } private final String mErrorType; private final String mName; } /** * Attempts to apply mutator to every matching view. Use this to update properties * in the view hierarchy. If accessor is non-null, it will be used to attempt to * prevent calls to the mutator if the property already has the intended value. */ public static class PropertySetVisitor extends ViewVisitor { public PropertySetVisitor(List<Pathfinder.PathElement> path, Caller mutator, Caller accessor) { super(path); mMutator = mutator; mAccessor = accessor; mOriginalValueHolder = new Object[1]; mOriginalValues = new WeakHashMap<View, Object>(); } @Override public void cleanup() { for (Map.Entry<View, Object> original:mOriginalValues.entrySet()) { final View changedView = original.getKey(); final Object originalValue = original.getValue(); if (null != originalValue) { mOriginalValueHolder[0] = originalValue; mMutator.applyMethodWithArguments(changedView, mOriginalValueHolder); } } } @Override public void accumulate(View found) { if (null != mAccessor) { final Object[] setArgs = mMutator.getArgs(); if (1 == setArgs.length) { final Object desiredValue = setArgs[0]; final Object currentValue = mAccessor.applyMethod(found); if (desiredValue == currentValue) { return; } if (null != desiredValue) { if (desiredValue instanceof Bitmap && currentValue instanceof Bitmap) { final Bitmap desiredBitmap = (Bitmap) desiredValue; final Bitmap currentBitmap = (Bitmap) currentValue; if (desiredBitmap.sameAs(currentBitmap)) { return; } } else if (desiredValue instanceof BitmapDrawable && currentValue instanceof BitmapDrawable) { final Bitmap desiredBitmap = ((BitmapDrawable) desiredValue).getBitmap(); final Bitmap currentBitmap = ((BitmapDrawable) currentValue).getBitmap(); if (desiredBitmap != null && desiredBitmap.sameAs(currentBitmap)) { return; } } else if (desiredValue.equals(currentValue)) { return; } } if (currentValue instanceof Bitmap || currentValue instanceof BitmapDrawable || mOriginalValues.containsKey(found)) { ; // Cache exactly one non-image original value } else { mOriginalValueHolder[0] = currentValue; if (mMutator.argsAreApplicable(mOriginalValueHolder)) { mOriginalValues.put(found, currentValue); } else { mOriginalValues.put(found, null); } } } } mMutator.applyMethod(found); } protected String name() { return "Property Mutator"; } private final Caller mMutator; private final Caller mAccessor; private final WeakHashMap<View, Object> mOriginalValues; private final Object[] mOriginalValueHolder; } private static class CycleDetector { /** * This function detects circular dependencies for all the views under the parent * of the updated view. The basic idea is to consider the views as a directed * graph and perform a DFS on all the nodes in the graph. If the current node is * in the DFS stack already, there must be a circle in the graph. To speed up the * search, all the parsed nodes will be removed from the graph. */ public boolean hasCycle(ArrayMap<View, ArrayList<View>> dependencyGraph) { ArrayList<View> dfsStack = new ArrayList<View>(); while (!dependencyGraph.isEmpty()) { View currentNode = dependencyGraph.keyAt(0); if (!detectSubgraphCycle(dependencyGraph, currentNode, dfsStack)) { return false; } } return true; } private boolean detectSubgraphCycle(ArrayMap<View, ArrayList<View>> dependencyGraph, View currentNode, ArrayList<View> dfsStack) { if (dfsStack.contains(currentNode)) { return false; } if (dependencyGraph.containsKey(currentNode)) { ArrayList<View> dependencies = dependencyGraph.remove(currentNode); dfsStack.add(currentNode); int size = dependencies.size(); for (int i = 0; i < size; i++) { if (!detectSubgraphCycle(dependencyGraph, dependencies.get(i), dfsStack)) { return false; } } dfsStack.remove(currentNode); } return true; } } public static class LayoutUpdateVisitor extends ViewVisitor { public LayoutUpdateVisitor(List<Pathfinder.PathElement> path, ArrayList<LayoutRule> args, String name, OnLayoutErrorListener onLayoutErrorListener) { super(path); mOriginalValues = new WeakHashMap<View, int[]>(); mArgs = args; mName = name; mAlive = true; mOnLayoutErrorListener = onLayoutErrorListener; mCycleDetector = new CycleDetector(); } @Override public void cleanup() { // TODO find a way to optimize this.. remove this visitor and trigger a re-layout?? for (Map.Entry<View, int[]> original:mOriginalValues.entrySet()) { final View changedView = original.getKey(); final int[] originalValue = original.getValue(); final RelativeLayout.LayoutParams originalParams = (RelativeLayout.LayoutParams) changedView.getLayoutParams(); for (int i = 0; i < originalValue.length; i++) { originalParams.addRule(i, originalValue[i]); } changedView.setLayoutParams(originalParams); } mAlive = false; } @Override public void visit(View rootView) { // this check is necessary - if the layout change is invalid, accumulate will send an error message // to the Web UI; before Web UI removes such change, this visit may get called by Android again and // thus send another error message to Web UI which leads to lots of weird problems if (mAlive) { getPathfinder().findTargetsInRoot(rootView, getPath(), this); } } // layout changes are performed on the children of found according to the LayoutRule @Override public void accumulate(View found) { ViewGroup parent = (ViewGroup) found; SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); for (int i = 0; i < count; i++) { View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } int size = mArgs.size(); for (int i = 0; i < size; i++) { LayoutRule layoutRule = mArgs.get(i); final View currentChild = idToChild.get(layoutRule.viewId); RelativeLayout.LayoutParams currentParams = (RelativeLayout.LayoutParams) currentChild.getLayoutParams(); final int[] currentRules = currentParams.getRules().clone(); if (currentRules[layoutRule.verb] == layoutRule.anchor) { continue; } if (mOriginalValues.containsKey(currentChild)) { ; // Cache exactly one set of rules per child view } else { mOriginalValues.put(currentChild, currentRules); } currentParams.addRule(layoutRule.verb, layoutRule.anchor); final Set<Integer> rules; if (mHorizontalRules.contains(layoutRule.verb)) { rules = mHorizontalRules; } else if (mVerticalRules.contains(layoutRule.verb)) { rules = mVerticalRules; } else { rules = null; } if (rules != null && !verifyLayout(rules, idToChild)) { cleanup(); mOnLayoutErrorListener.onLayoutError(new LayoutErrorMessage("circular_dependency", mName)); return; } currentChild.setLayoutParams(currentParams); } } private boolean verifyLayout(Set<Integer> rules, SparseArray<View> idToChild) { ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>(); int size = idToChild.size(); for (int i = 0; i < size; i++) { final View child = idToChild.valueAt(i); final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams(); int[] layoutRules = childLayoutParams.getRules(); ArrayList<View> dependencies = new ArrayList<View>(); for (int rule : rules) { int dependencyId = layoutRules[rule]; if (dependencyId > 0 && dependencyId != child.getId()) { dependencies.add(idToChild.get(dependencyId)); } } dependencyGraph.put(child, dependencies); } return mCycleDetector.hasCycle(dependencyGraph); } protected String name() { return "Layout Update"; } private final WeakHashMap<View, int[]> mOriginalValues; private final ArrayList<LayoutRule> mArgs; private final String mName; private static final Set<Integer> mHorizontalRules = new HashSet<Integer>(Arrays.asList( RelativeLayout.LEFT_OF, RelativeLayout.RIGHT_OF, RelativeLayout.ALIGN_LEFT, RelativeLayout.ALIGN_RIGHT )); private static final Set<Integer> mVerticalRules = new HashSet<Integer>(Arrays.asList( RelativeLayout.ABOVE, RelativeLayout.BELOW, RelativeLayout.ALIGN_BASELINE, RelativeLayout.ALIGN_TOP, RelativeLayout.ALIGN_BOTTOM )); private boolean mAlive; private final OnLayoutErrorListener mOnLayoutErrorListener; private final CycleDetector mCycleDetector; } public static class LayoutRule { public LayoutRule(int vi, int v, int a) { viewId = vi; verb = v; anchor = a; } public final int viewId; public final int verb; public final int anchor; } /** * Adds an accessibility event, which will fire OnEvent, to every matching view. */ public static class AddAccessibilityEventVisitor extends EventTriggeringVisitor { public AddAccessibilityEventVisitor(List<Pathfinder.PathElement> path, int accessibilityEventType, String eventName, OnEventListener listener) { super(path, eventName, listener, false); mEventType = accessibilityEventType; mWatching = new WeakHashMap<View, TrackingAccessibilityDelegate>(); } @Override public void cleanup() { for (final Map.Entry<View, TrackingAccessibilityDelegate> entry:mWatching.entrySet()) { final View v = entry.getKey(); final TrackingAccessibilityDelegate toCleanup = entry.getValue(); final View.AccessibilityDelegate currentViewDelegate = getOldDelegate(v); if (currentViewDelegate == toCleanup) { v.setAccessibilityDelegate(toCleanup.getRealDelegate()); } else if (currentViewDelegate instanceof TrackingAccessibilityDelegate) { final TrackingAccessibilityDelegate newChain = (TrackingAccessibilityDelegate) currentViewDelegate; newChain.removeFromDelegateChain(toCleanup); } else { // Assume we've been replaced, zeroed out, or for some other reason we're already gone. // (This isn't too weird, for example, it's expected when views get recycled) } } mWatching.clear(); } @Override public void accumulate(View found) { final View.AccessibilityDelegate realDelegate = getOldDelegate(found); if (realDelegate instanceof TrackingAccessibilityDelegate) { final TrackingAccessibilityDelegate currentTracker = (TrackingAccessibilityDelegate) realDelegate; if (currentTracker.willFireEvent(getEventName())) { return; // Don't double track } } // We aren't already in the tracking call chain of the view final TrackingAccessibilityDelegate newDelegate = new TrackingAccessibilityDelegate(realDelegate); found.setAccessibilityDelegate(newDelegate); mWatching.put(found, newDelegate); } @Override protected String name() { return getEventName() + " event when (" + mEventType + ")"; } private View.AccessibilityDelegate getOldDelegate(View v) { View.AccessibilityDelegate ret = null; try { Class<?> klass = v.getClass(); Method m = klass.getMethod("getAccessibilityDelegate"); ret = (View.AccessibilityDelegate) m.invoke(v); } catch (NoSuchMethodException e) { // In this case, we just overwrite the original. } catch (IllegalAccessException e) { // In this case, we just overwrite the original. } catch (InvocationTargetException e) { Log.w(LOGTAG, "getAccessibilityDelegate threw an exception when called.", e); } return ret; } private class TrackingAccessibilityDelegate extends View.AccessibilityDelegate { public TrackingAccessibilityDelegate(View.AccessibilityDelegate realDelegate) { mRealDelegate = realDelegate; } public View.AccessibilityDelegate getRealDelegate() { return mRealDelegate; } public boolean willFireEvent(final String eventName) { if (getEventName() == eventName) { return true; } else if (mRealDelegate instanceof TrackingAccessibilityDelegate) { return ((TrackingAccessibilityDelegate) mRealDelegate).willFireEvent(eventName); } else { return false; } } public void removeFromDelegateChain(final TrackingAccessibilityDelegate other) { if (mRealDelegate == other) { mRealDelegate = other.getRealDelegate(); } else if (mRealDelegate instanceof TrackingAccessibilityDelegate) { final TrackingAccessibilityDelegate child = (TrackingAccessibilityDelegate) mRealDelegate; child.removeFromDelegateChain(other); } else { // We can't see any further down the chain, just return. } } @Override public void sendAccessibilityEvent(View host, int eventType) { if (eventType == mEventType) { fireEvent(host); } if (null != mRealDelegate) { mRealDelegate.sendAccessibilityEvent(host, eventType); } } private View.AccessibilityDelegate mRealDelegate; } private final int mEventType; private final WeakHashMap<View, TrackingAccessibilityDelegate> mWatching; } /** * Installs a TextWatcher in each matching view. Does nothing if matching views are not TextViews. */ public static class AddTextChangeListener extends EventTriggeringVisitor { public AddTextChangeListener(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener) { super(path, eventName, listener, true); mWatching = new HashMap<TextView, TextWatcher>(); } @Override public void cleanup() { for (final Map.Entry<TextView, TextWatcher> entry:mWatching.entrySet()) { final TextView v = entry.getKey(); final TextWatcher watcher = entry.getValue(); v.removeTextChangedListener(watcher); } mWatching.clear(); } @Override public void accumulate(View found) { if (found instanceof TextView) { final TextView foundTextView = (TextView) found; final TextWatcher watcher = new TrackingTextWatcher(foundTextView); final TextWatcher oldWatcher = mWatching.get(foundTextView); if (null != oldWatcher) { foundTextView.removeTextChangedListener(oldWatcher); } foundTextView.addTextChangedListener(watcher); mWatching.put(foundTextView, watcher); } } @Override protected String name() { return getEventName() + " on Text Change"; } private class TrackingTextWatcher implements TextWatcher { public TrackingTextWatcher(View boundTo) { mBoundTo = boundTo; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; // Nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { ; // Nothing } @Override public void afterTextChanged(Editable s) { fireEvent(mBoundTo); } private final View mBoundTo; } private final Map<TextView, TextWatcher> mWatching; } /** * Monitors the view tree for the appearance of matching views where there were not * matching views before. Fires only once per traversal. */ public static class ViewDetectorVisitor extends EventTriggeringVisitor { public ViewDetectorVisitor(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener) { super(path, eventName, listener, false); mSeen = false; } @Override public void cleanup() { ; // Do nothing, we don't have anything to leak :) } @Override public void accumulate(View found) { if (found != null && !mSeen) { fireEvent(found); } mSeen = (found != null); } @Override protected String name() { return getEventName() + " when Detected"; } private boolean mSeen; } private static abstract class EventTriggeringVisitor extends ViewVisitor { public EventTriggeringVisitor(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener, boolean debounce) { super(path); mListener = listener; mEventName = eventName; mDebounce = debounce; } protected void fireEvent(View found) { mListener.OnEvent(found, mEventName, mDebounce); } protected String getEventName() { return mEventName; } private final OnEventListener mListener; private final String mEventName; private final boolean mDebounce; } /** * Scans the View hierarchy below rootView, applying it's operation to each matching child view. */ public void visit(View rootView) { mPathfinder.findTargetsInRoot(rootView, mPath, this); } /** * Removes listeners and frees resources associated with the visitor. Once cleanup is called, * the ViewVisitor should not be used again. */ public abstract void cleanup(); protected ViewVisitor(List<Pathfinder.PathElement> path) { mPath = path; mPathfinder = new Pathfinder(); } protected List<Pathfinder.PathElement> getPath() { return mPath; } protected Pathfinder getPathfinder() { return mPathfinder; } protected abstract String name(); private final List<Pathfinder.PathElement> mPath; private final Pathfinder mPathfinder; private static final String LOGTAG = "MixpanelAPI.ViewVisitor"; }
package com.netflix.priam.compress; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import org.apache.commons.io.IOUtils; import org.xerial.snappy.SnappyInputStream; /** * Class to generate compressed chunks of data from an input stream using * SnappyCompression */ public class SnappyCompression implements ICompression { private static final int BUFFER = 2 * 1024; @Override public Iterator<byte[]> compress(InputStream is, long chunkSize) throws IOException { return new ChunkedStream(is, chunkSize); } @Override public void decompressAndClose(InputStream input, OutputStream output) throws IOException { try { decompress(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } private void decompress(InputStream input, OutputStream output) throws IOException { SnappyInputStream is = new SnappyInputStream(new BufferedInputStream(input)); byte data[] = new byte[BUFFER]; BufferedOutputStream dest1 = new BufferedOutputStream(output, BUFFER); try { int c; while ((c = is.read(data, 0, BUFFER)) != -1) { dest1.write(data, 0, c); } } finally { IOUtils.closeQuietly(dest1); IOUtils.closeQuietly(is); } } }
package com.segment.android.utils; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.telephony.TelephonyManager; import android.text.TextUtils; import java.util.UUID; public final class Utils { private Utils() { throw new AssertionError("No instances"); } public static boolean hasPermission(Context context, String permission) { return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } /** Returns true if the application has the given feature. */ public static boolean hasFeature(Context context, String feature) { return context.getPackageManager().hasSystemFeature(feature); } /** Returns the system service for the given string. */ @SuppressWarnings("unchecked") public static <T> T getSystemService(Context context, String serviceConstant) { return (T) context.getSystemService(serviceConstant); } /** Returns true if the string is null, or empty (when trimmed). */ public static boolean isNullOrEmpty(String text) { // Rather than using text.trim().length() == 0, use getTrimmedLength to avoid allocating an // extra string object return TextUtils.isEmpty(text) || TextUtils.getTrimmedLength(text) == 0; } /** Creates a unique device id to anonymously track a user. */ public static String getDeviceId(Context context) { // credit method: Amplitude's Android library // Android ID // Issues on 2.2, some phones have same Android ID due to manufacturer // error String androidId = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); if (!(isNullOrEmpty(androidId) || androidId.equals("9774d56d682e549c"))) { return androidId; } // Serial number // Guaranteed to be on all non phones in 2.3+ if (!isNullOrEmpty(Build.SERIAL)) { return Build.SERIAL; } if (hasPermission(context, Manifest.permission.READ_PHONE_STATE) && hasFeature(context, PackageManager.FEATURE_TELEPHONY)) { TelephonyManager telephonyManager = getSystemService(context, Context.TELEPHONY_SERVICE); String telephonyId = telephonyManager.getDeviceId(); if (!isNullOrEmpty(telephonyId)) { return telephonyId; } } // If this still fails, generate random identifier that does not persist // across installations return UUID.randomUUID().toString(); } }
package com.persado.oss.quality.stevia.testng; import com.persado.oss.quality.stevia.selenium.core.SteviaContext; import com.persado.oss.quality.stevia.selenium.core.WebComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.Reporter; import java.util.List; public class Verify extends WebComponent { /** * The log. */ private static final Logger VERIFY_LOG = LoggerFactory.getLogger("VerifyLog"); /** * The pass color. */ private static final String PASS_COLOR = "Lime"; /** * The fail color. */ private static final String FAIL_COLOR = "OrangeRed"; private static final String ELEMENT_LOCATOR = "The element with locator '"; private static final String TEXT = "The text '"; private static final String IS_VISIBLE = "' is visible!"; private static final String IS_NOT_VISIBLE = "' is not visible!"; private static final String FOUND = "' was found!"; private static final String NOT_FOUND = "' was not found!"; private static final String FOUND_WITH_TEXT = "' was found with text '"; private static final String NOT_FOUND_WITH_TEXT = "' was not found with text '"; private static final String FOUND_CONTAINING_TEXT = "' was found to contain text '"; private static final String NOT_FOUND_CONTAINING_TEXT = "' was not found to contain text '"; private static final String FOUND_WITH_VALUE = "' was found with value '"; private static final String NOT_FOUND_WITH_VALUE = "' was not found with value '"; private static final String FOUND_CONTAINING_VALUE = "' was found to contain value '"; private static final String NOT_FOUND_CONTAINING_VALUE = "' was not found to contain value '"; private static final String FOUND_EDITABLE = "' was found editable!"; private static final String FOUND_DISABLED = "' was found disabled!"; private static final String FOUND_SELECTED = "' was found selected!"; private static final String NOT_FOUND_SELECTED = "' was not found selected!"; private static final String IS_EQUAL = "' is equal with '"; private static final String IS_NOT_EQUAL = "' is not equal with '"; private static final String ELEMENT_LOCATOR_ATTRIBUTE = "' attribute of element with locator '"; private static final String CONTAINED_IN_LIST = "' is contained in the list'!"; private static final String NOT_CONTAINED_IN_LIST = "' is not contained in the list'!"; private static final String FOUND_WITH_OPTIONS = "' was found with options '"; private static final String NOT_FOUND_WITH_OPTIONS = "' was not found options '"; private static final String FOUND_WITH_SELECTED_OPTIONS = "' was found with selected options '"; private static final String NOT_FOUND_WITH_SELECTED_OPTIONS = "' was not found with selected options '"; private static final String FOUND_WITH_SELECTED_OPTION = "' was found with selected option '"; private static final String NOT_FOUND_WITH_SELECTED_OPTION = "' was not found with selected option '"; private static final String FOUND_ALERT_WITH_MESSAGE = "There was an alert with message '"; private static final String NOT_FOUND_ALERT_WITH_MESSAGE = "There was an alert with message '"; private static final String TABLE_ELEMENT = "The table element '"; private static final String HAS_ATTRIBUTE = "' has the attribute '"; private static final String HAS_NOT_ATTRIBUTE = "' has not the attribute '"; /** * Instantiates a new verify. */ public Verify() { System.setProperty("org.uncommons.reportng.escape-output", "false"); } /** * Info. * * @param message the message */ public void info(String message) { VERIFY_LOG.info(message); Reporter.log("<p class=\"testOutput\" style=\"color:green; font-size:1em;\">" + message + "</p>"); } /** * Warn. * * @param message the message */ public void warn(String message) { VERIFY_LOG.warn(message); Reporter.log("<p class=\"testOutput\" style=\"color:orange; font-size:1em;\">" + message + "</p>"); } /** * Error. * * @param message the message */ public void error(String message) { VERIFY_LOG.error(message); Reporter.log("<p class=\"testOutput\" style=\"color:red; font-size:1em;\">" + message + "</p>"); } /** * Check that text is present. * * @param text the text */ public void textPresent(String text) { try { Assert.assertTrue(controller().isTextPresent(text)); info(TEXT + text + FOUND); } catch (AssertionError e) { error(TEXT + text + NOT_FOUND); throw e; } } /** * Check that text is not present. * * @param text the text under examination */ public void textNotPresent(String text) { try { Assert.assertTrue(controller().isTextNotPresent(text)); info(TEXT + text + NOT_FOUND); } catch (AssertionError e) { error(TEXT + text + FOUND); throw e; } } /** * Check that an Element is present * * @param locator the locator of an element */ public void elementPresent(String locator) { try { Assert.assertTrue(controller().isComponentPresent(locator)); info(ELEMENT_LOCATOR + locator + FOUND); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + NOT_FOUND); throw e; } } /** * Check that an Element is present for a specific timeframe. * * @param locator the locator Check that an Element is present * @param seconds the time in seconds that the element must remain present */ public void elementPresent(String locator, long seconds) { try { Assert.assertTrue(controller().isComponentPresent(locator, seconds)); info(ELEMENT_LOCATOR + locator + FOUND); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + NOT_FOUND); throw e; } } /** * Check that an Element is not present. * * @param locator the locator of the element */ public void elementNotPresent(String locator) { try { Assert.assertTrue(controller().isComponentNotPresent(locator)); info(ELEMENT_LOCATOR + locator + NOT_FOUND); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + FOUND); throw e; } } /** * Check that an Element is visible. * * @param locator the locator of an element */ public void elementVisible(String locator) { try { Assert.assertTrue(controller().isComponentVisible(locator)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + IS_VISIBLE); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + IS_NOT_VISIBLE); throw e; } } /** * Check that an Element is visible. * * @param locator the locator of the element * @param seconds the least time in seconds that element must remain visible */ public void elementVisible(String locator, long seconds) { try { Assert.assertTrue(controller().isComponentVisible(locator, seconds)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + IS_VISIBLE); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + IS_NOT_VISIBLE); throw e; } } /** * Check that an Element is not visible. * * @param locator the locator of the element */ public void elementNotVisible(String locator) { try { Assert.assertTrue(controller().isComponentNotVisible(locator)); info(ELEMENT_LOCATOR + locator + IS_NOT_VISIBLE); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + IS_VISIBLE); throw e; } } /** * Check that an Element is not visible. * * @param locator the locator of the element * @param seconds the max time in seconds after which element should become invisible */ public void elementNotVisible(String locator, long seconds) { try { Assert.assertTrue(controller().isComponentNotVisible(locator, seconds)); info(ELEMENT_LOCATOR + locator + IS_NOT_VISIBLE); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + IS_VISIBLE); throw e; } } /** * Check the value of an element . * * @param locator the element locator * @param expectedValue the expected value */ public void value(String locator, String expectedValue) { try { Assert.assertEquals(controller().getInputValue(locator), expectedValue); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_VALUE + expectedValue + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_VALUE + expectedValue + "'!"); throw e; } } /** * Check text in an element. * * @param locator the locator of the element * @param expectedText the expected text */ public void text(String locator, String expectedText) { try { Assert.assertEquals(controller().getText(locator), expectedText); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_TEXT + expectedText + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_TEXT + expectedText + "'!"); throw e; } } /** * Check text in an element based on presence (not visibility) of the element * * @param locator the locator of the element * @param expectedText the expected text */ public void textPresenceBased(String locator, String expectedText) { try { Assert.assertEquals(controller().waitForElementPresence(locator).getText(), expectedText); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_TEXT + expectedText + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_TEXT + expectedText + "'!"); throw e; } } /** * Check trimmed text in an element. * * @param locator the locator of the element * @param expectedText the expected text */ public void trimmedText(String locator, String expectedText) { try { Assert.assertEquals(controller().getText(locator).trim(), expectedText); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_TEXT + expectedText + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_TEXT + expectedText + "'!"); throw e; } } /** * Check that an element contains a specific text. * * @param locator the locator of the element * @param expectedText the expected text */ public void containsText(String locator, String expectedText) { if (controller().getText(locator).contains(expectedText)) { highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_CONTAINING_TEXT + expectedText + "'!"); } else { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_CONTAINING_TEXT + expectedText + "'!"); throw new AssertionError(ELEMENT_LOCATOR + locator + NOT_FOUND_CONTAINING_TEXT + expectedText + "'!"); } } /** * Checks if the specified input element is editable * * @param locator the locator of the element */ public void editable(String locator) { try { Assert.assertTrue(controller().isComponentEditable(locator)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_EDITABLE); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + FOUND_DISABLED); throw e; } } /** * Checks if a component disabled. This means that no write/edit actions are allowed * * @param locator the locator of the component */ public void disabled(String locator) { try { Assert.assertTrue(controller().isComponentDisabled(locator)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_DISABLED); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + FOUND_EDITABLE); throw e; } } /** * Check that an element (check box, radio button etc) is selected. * * @param locator the locator of the element */ public void selected(String locator) { try { Assert.assertTrue(controller().isComponentSelected(locator)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_SELECTED); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_SELECTED); throw e; } } /** * Check that an element (check box, radio button etc) is selected. * * @param locator the locator of the element */ public void selectedAndPresent(String locator) { try { Assert.assertTrue(controller().waitForElementPresence(locator).isSelected()); info(ELEMENT_LOCATOR + locator + FOUND_SELECTED); } catch (AssertionError e) { error(ELEMENT_LOCATOR + locator + NOT_FOUND_SELECTED); throw e; } } /** * Check that a check box, field, radio button is not selected. * * @param locator the locator of the field you want to find unchecked */ public void notSelected(String locator) { try { Assert.assertTrue(controller().isComponentNotSelected(locator)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + NOT_FOUND_SELECTED); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + FOUND_SELECTED); throw e; } } /** * Text is contained in a table, under a specific table header, in the row of a specific element * * @param locator the locator of the table * @param elementName The element that is situated in the same row with the expected text * @param headerName the header name under which the element is expected * @param expectedText the expected text */ public void tableElementTextUnderHeader(String locator, String elementName, String headerName, String expectedText) { try { Assert.assertEquals(controller().getTableElementTextUnderHeader(locator, elementName, headerName), expectedText); highlightPass(controller().getTableElementSpecificHeaderLocator(locator, elementName, headerName)); info(TABLE_ELEMENT + elementName + FOUND_WITH_TEXT + expectedText + "' for header '" + headerName + "'!"); } catch (AssertionError e) { highlightFail(controller().getTableElementSpecificHeaderLocator(locator, elementName, headerName)); error(TABLE_ELEMENT + elementName + NOT_FOUND_WITH_TEXT + expectedText + "' for header '" + headerName + "'!"); throw e; } } /** * Text is contained in table in specific row and column. * * @param locator the locator of the table * @param row the row of the table where text is expected * @param column the column of the table where text is expected * @param expectedText the expected text for the specified row and column of the table */ public void tableElementTextForSpecificRowAndColumn(String locator, String row, String column, String expectedText) { try { Assert.assertEquals(controller().getTableElementTextForRowAndColumn(locator, row, column), expectedText); highlightPass(controller().getTableElementSpecificRowAndColumnLocator(locator, row, column)); info("The table element in row '" + row + "' and column '" + column + FOUND_WITH_TEXT + expectedText + "'!"); } catch (AssertionError e) { highlightFail(controller().getTableElementSpecificRowAndColumnLocator(locator, row, column)); error("The table element in row '" + row + "' and column '" + column + NOT_FOUND_WITH_TEXT + expectedText + "'!"); throw e; } } /** * Table element row. Check that an element can be found at a specific table row * * @param locator the locator * @param elementName the element name you expect to find in table * @param expectedRow the expected row for your element */ public void tableElementAtRowPosition(String locator, String elementName, String expectedRow) { try { Assert.assertEquals(controller().getTableElementRowPosition(locator, elementName), expectedRow); info(TABLE_ELEMENT + elementName + "' was found in row '" + expectedRow + "'!"); } catch (AssertionError e) { error(TABLE_ELEMENT + elementName + "' was not found in row '" + expectedRow + "'!"); throw e; } } /** * Table elements. Check that current table elements are the expected ones * * @param locator the locator of the table * @param expectedArray the expected array for comparison with the actual array */ public void tableElements(String locator, String[][] expectedArray) { String[][] actualArray = controller().getTableElements2DArray(locator); Assert.assertEquals(actualArray.length, expectedArray.length, "The arrays have not the same length"); boolean errorFound = false; for (int i = 0; i < expectedArray.length; i++) { for (int j = 0; j < expectedArray[i].length; j++) { if (expectedArray[i][j].equals(actualArray[i][j])) { highlightPass(controller().getTableElementSpecificRowAndColumnLocator(locator, String.valueOf(i + 1), String.valueOf(j + 1))); } else { highlightFail(controller().getTableElementSpecificRowAndColumnLocator(locator, String.valueOf(i + 1), String.valueOf(j + 1))); error("The table elements for row " + (i + 1) + " and column " + (j + 1) + " are not equal! EXPECTED VALUE: " + expectedArray[i][j] + " - ACTUAL VALUE: " + actualArray[i][j]); errorFound = true; } } } if (errorFound) { throw new AssertionError("The table elements are not equal"); } info("The table elements are equal"); } /** * @param locator * @param headerName * @param tableRecords */ public void allTableRecordsUnderHeader(String locator, String headerName, List<String> tableRecords) { List<String> actualRecords = controller().getTableRecordsUnderHeader(locator, headerName); try { Assert.assertEquals(actualRecords, tableRecords); for (String element : tableRecords) { highlightPass(controller().getTableElementSpecificHeaderLocator(locator, element, headerName)); } info("The table records under header '" + headerName + "' are correct"); } catch (AssertionError e) { error("The table records under header '" + headerName + "' are not correct"); throw e; } } /** * Text is contained in table, in a column with a specific header. * * @param locator the locator of the table * @param headerName the header name of the column, where the text is expected * @param expectedText the expected text in the specified location */ public void textIsContainedInTableRecordsUnderHeader(String locator, String headerName, String expectedText) { List<String> records = controller().getTableRecordsUnderHeader(locator, headerName); if (records.contains(expectedText)) { highlightPass(controller().getTableElementSpecificHeaderLocator(locator, expectedText, headerName)); info("The '" + expectedText + "' was found with in table with locator '" + locator + "' under header '" + headerName + "'"); return; } highlightFail(locator); error("The '" + expectedText + "' was not found with in table with locator '" + locator + "' under header '" + headerName + "'"); throw new AssertionError(); } /** * Text is not contained in a table, in a column with a specific header * * @param locator the locator of the table * @param headerName the header name of the column, where the text is not expected * @param expectedText the text that is not expected in the specified location */ public void textIsNotContainedInTableRecordsUnderHeader(String locator, String headerName, String expectedText) { List<String> records = controller().getTableRecordsUnderHeader(locator, headerName); if (!records.contains(expectedText)) { highlightPass(locator); info("The '" + expectedText + "' was not found not with in table with locator '" + locator + "' under header '" + headerName + "'"); return; } highlightFail(controller().getTableElementSpecificHeaderLocator(locator, expectedText, headerName)); error("The '" + expectedText + "' was found with in table with locator '" + locator + "' under header '" + headerName + "'"); throw new AssertionError(); } /** * List options. Check all options available in a list * * @param locator the locator of the list * @param expectedOptions the expected available options to found in a list */ public void allListOptions(String locator, List<String> expectedOptions) { try { Assert.assertEquals(controller().getAllListOptions(locator), expectedOptions); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_OPTIONS + expectedOptions + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_OPTIONS + expectedOptions + "'!"); throw e; } } /** * List options. Check all options available in a list without considering the elements order * * @param locator the locator of the list * @param expectedOptions the expected available options to found in a list */ public void allListOptionsNoOrder(String locator, List<String> expectedOptions) { List<String> actualOptions = controller().getAllListOptions(locator); try { Assert.assertEqualsNoOrder(actualOptions.toArray(new String[actualOptions.size()]), expectedOptions.toArray(new String[expectedOptions.size()])); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_OPTIONS + expectedOptions + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_OPTIONS + expectedOptions + "'!"); throw e; } } /** * List options. Checks if some options are selected in a list * * @param locator the locator of the list * @param expectedOptions the expected options in the specified list */ public void selectedListOptions(String locator, List<String> expectedOptions) { try { Assert.assertEquals(controller().getSelectedOptions(locator), expectedOptions); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_SELECTED_OPTIONS + expectedOptions + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_SELECTED_OPTIONS + expectedOptions + "'!"); throw e; } } /** * Selected list option. Checks if an option is selected in a list * * @param locator the locator of the list * @param expectedOption the expected option selected in the list */ public void selectedListOption(String locator, String expectedOption) { try { Assert.assertEquals(controller().getSelectedOption(locator), expectedOption); highlightPass(locator); info(ELEMENT_LOCATOR + locator + FOUND_WITH_SELECTED_OPTION + expectedOption + "'!"); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + NOT_FOUND_WITH_SELECTED_OPTION + expectedOption + "'!"); throw e; } } /** * Equal. Check two objects for equality * * @param obj1 the obj1 you want to check * @param obj2 the obj2 you want to check */ public void equal(Object obj1, Object obj2) { try { Assert.assertEquals(obj1, obj2); info("The '" + obj1 + IS_EQUAL + obj2 + "'!"); } catch (AssertionError e) { error("The '" + obj1 + IS_NOT_EQUAL + obj2 + "'!"); throw e; } } /** * Non Equality . Check two objects for non equality * * @param obj1 the obj1 you want to check * @param obj2 the obj2 you want to check */ public void notEqual(Object obj1, Object obj2) { try { Assert.assertNotEquals(obj1, obj2); info("The '" + obj1 + IS_NOT_EQUAL + obj2 + "'!"); } catch (AssertionError e) { error("The '" + obj1 + IS_EQUAL + obj2 + "'!"); throw e; } } /** * Verify that the element has the given attribute * * @param locator * @param attribute */ public void hasAttribute(String locator, String attribute) { try { Assert.assertNotNull(controller().getAttributeValue(locator, attribute)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + HAS_ATTRIBUTE + attribute); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + HAS_NOT_ATTRIBUTE + attribute); throw e; } } /** * Verify that the element has the given attribute * * @param locator * @param attribute */ public void hasNotAttribute(String locator, String attribute) { try { Assert.assertNull(controller().getAttributeValue(locator, attribute)); highlightPass(locator); info(ELEMENT_LOCATOR + locator + HAS_NOT_ATTRIBUTE + attribute); } catch (AssertionError e) { highlightFail(locator); error(ELEMENT_LOCATOR + locator + HAS_ATTRIBUTE + attribute); throw e; } } /** * Attribute value. * * @param locator the locator of the element * @param attribute the attribute of the element under examination * @param desiredValue the desired value that the attribute must have */ public void attributeValue(String locator, String attribute, String desiredValue) { try { Assert.assertEquals(controller().getAttributeValue(locator, attribute), desiredValue); highlightPass(locator); info("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + FOUND_WITH_VALUE + desiredValue + "'!"); } catch (AssertionError e) { highlightFail(locator); error("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + NOT_FOUND_WITH_VALUE + desiredValue + "'!"); throw e; } } /** * Attribute contains value. * * @param locator the locator of the element * @param attribute the attribute of the element under examination * @param desiredValue the desired value to be contained in attribute */ public void attributeContainsValue(String locator, String attribute, String desiredValue) { if (controller().getAttributeValue(locator, attribute).contains(desiredValue)) { highlightPass(locator); info("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + FOUND_CONTAINING_VALUE + desiredValue + "'!"); } else { highlightFail(locator); error("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + NOT_FOUND_CONTAINING_VALUE + desiredValue + "'!"); throw new AssertionError("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + NOT_FOUND_CONTAINING_VALUE + desiredValue + "'!"); } } /** * Attribute does not contain value. * * @param locator the locator of the element * @param attribute the attribute of the element under examination * @param desiredValue the desired value not to be contained in attribute */ public void attributeDoesNotContainValue(String locator, String attribute, String desiredValue) { if (!controller().getAttributeValue(locator, attribute).contains(desiredValue)) { highlightPass(locator); info("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + NOT_FOUND_CONTAINING_VALUE + desiredValue + "'!"); } else { highlightFail(locator); error("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + FOUND_CONTAINING_VALUE + desiredValue + "'!"); throw new AssertionError("The '" + attribute + ELEMENT_LOCATOR_ATTRIBUTE + locator + FOUND_CONTAINING_VALUE + desiredValue + "'!"); } } /** * Element contained in list. * * @param list the list you want to search into * @param element the element you want to be present in the list */ public void elementContainedInList(List<?> list, Object element) { if (list.contains(element)) { info("The '" + element + CONTAINED_IN_LIST); } else { error("The '" + element + NOT_CONTAINED_IN_LIST); throw new AssertionError("The '" + element + NOT_CONTAINED_IN_LIST); } } /** * Element is not contained in a list. * * @param list the list you want to search into * @param element the element you want to be not present in the list */ public void elementNotContainedInList(List<?> list, Object element) { if (!list.contains(element)) { info("The '" + element + NOT_CONTAINED_IN_LIST); } else { error("The '" + element + CONTAINED_IN_LIST); throw new AssertionError("The '" + element + CONTAINED_IN_LIST); } } /** * Alert text. * * @param alertText the alert text */ public void alertText(String alertText) { try { Assert.assertEquals(controller().getAlertText(), alertText); info(FOUND_ALERT_WITH_MESSAGE + alertText + "'!"); } catch (AssertionError e) { error(NOT_FOUND_ALERT_WITH_MESSAGE + alertText + "'!"); throw e; } } private void highlightPass(String locator) { if (SteviaContext.getParam("highlight").equals("true")) { controller().highlight(locator, PASS_COLOR); } } private void highlightFail(String locator) { if (SteviaContext.getParam("highlight").equals("true")) { controller().highlight(locator, FAIL_COLOR); } } }
package com.primeradiants.oniri.novent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Service; import com.primeradiants.hibernate.util.HibernateUtil; import com.primeradiants.oniri.user.UserEntity; import org.apache.commons.io.FileUtils; /** * Simple novent utility. * @author Shanira * @since 0.1.0 */ @Service public class NoventManager { private SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory(); private static final String USER = "user"; private static final String ID = "id"; private static final String NOVENT = "novent"; private static final String NOVENT_FOLDER = "/var/primeradiants/oniri-data/novents/"; /** * Returns a novent based on id. * @param id the id of the novent * @return the NoventEntity object, or null if the novent cannot be found including null id. */ public NoventEntity getNovent(Integer id) { if(id == null) return null; Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session .createCriteria(NoventEntity.class) .add(Restrictions.eq(ID, id)) .setMaxResults(1); NoventEntity novent = (NoventEntity) criteria.uniqueResult(); session.getTransaction().commit(); return novent; } /** * Return all the novents in store * @return a List of {@link com.primeradiants.oniri.novent.NoventEntity} */ @SuppressWarnings("unchecked") public List<NoventEntity> getAllNovents() { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session .createCriteria(NoventEntity.class); List<NoventEntity> result = (List<NoventEntity>) criteria.list(); session.getTransaction().commit(); return result; } /** * Persist a new novent in database * @param title The title of the novent * @param authors The author list * @param description The description of the novent * @param coverFile The cover of the novent * @param noventFile The novent archive * @return The {@link com.primeradiants.oniri.novent.NoventEntity} * @throws IOException */ public NoventEntity createNoven(String title, List<String> authors, String description, File coverFile, File noventFile) throws IOException { NoventEntity noventEntity = new NoventEntity(0, title, authors, description, new Date(), null, null); Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); session.save(noventEntity); File folder = new File(NOVENT_FOLDER + noventEntity.getId()+ "/"); folder.mkdirs(); File cover = new File(NOVENT_FOLDER + noventEntity.getId() + "/" + coverFile.getName()); FileUtils.copyFile(coverFile, cover); File novent = new File(NOVENT_FOLDER + noventEntity.getId() + "/" + noventFile.getName()); FileUtils.copyFile(noventFile, novent); noventEntity.setCoverPath(cover.getAbsolutePath()); noventEntity.setNoventPath(novent.getAbsolutePath()); session.saveOrUpdate(noventEntity); session.getTransaction().commit(); return noventEntity; } /** * Return all the novents of the given user * @param user the user object * @return a List of {@link com.primeradiants.oniri.novent.NoventEntity} */ @SuppressWarnings("unchecked") public List<NoventEntity> getAllUserNovents(UserEntity user) { List<NoventEntity> result = new ArrayList<NoventEntity>(); if(user == null) return result; Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session .createCriteria(UserNoventEntity.class) .add(Restrictions.eq(USER, user)); List<UserNoventEntity> userNoventEntities = (List<UserNoventEntity>) criteria.list(); session.getTransaction().commit(); for(UserNoventEntity userNoventEntity : userNoventEntities) result.add(userNoventEntity.getNovent()); return result; } /** * Create a link between a user and a novent he just purchased * @param user The user that will own the novent * @param novent The novent that will be owned * @return The object representing the link between user and novent */ public UserNoventEntity createUserNoventLink(UserEntity user, NoventEntity novent) { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session .createCriteria(UserNoventEntity.class) .add(Restrictions.eq(USER, user)) .add(Restrictions.eq(NOVENT, novent)) .setMaxResults(1); UserNoventEntity userNoventEntity = (UserNoventEntity) criteria.uniqueResult(); //Creating link only if it doesn't already exists if(userNoventEntity == null) { userNoventEntity = new UserNoventEntity(0, user, novent, new Date()); session.save(userNoventEntity); } session.getTransaction().commit(); return userNoventEntity; } /** * Check if a user own a particular novent * @param user The user * @param novent The novent * @return a boolean value */ public boolean doesUserOwnNovent(UserEntity user, NoventEntity novent) { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session .createCriteria(UserNoventEntity.class) .add(Restrictions.eq(USER, user)) .add(Restrictions.eq(NOVENT, novent)) .setMaxResults(1); UserNoventEntity link = (UserNoventEntity) criteria.uniqueResult(); session.getTransaction().commit(); return (link != null); } }
package annotator.find; import annotator.Main; import java.io.*; import java.util.*; import javax.tools.*; import com.sun.source.tree.*; import com.sun.source.util.*; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.tree.JCTree.*; import javax.lang.model.element.Modifier; import com.google.common.collect.*; import plume.Pair; /** * A {@code TreeScanner} that is able to locate program elements in an * AST based on {@code Criteria}. It is used to scan a tree and return a * mapping of source positions (as character offsets) to insertion text. */ public class TreeFinder extends TreeScanner<Void, List<Insertion>> { static public boolean debug = false; private static void debug(String message) { if (debug) System.out.println(message); } private static void debug(String message, Object... args) { if (debug) { System.out.printf(message, args); if (! message.endsWith("%n")) { System.out.println(); } } } public static TreePath largestContainingArray(TreePath p) { if (p.getLeaf().getKind() != Tree.Kind.ARRAY_TYPE) { return null; } while (p.getParentPath().getLeaf().getKind() == Tree.Kind.ARRAY_TYPE) { p = p.getParentPath(); } assert p.getLeaf().getKind() == Tree.Kind.ARRAY_TYPE; return p; } /** * Determines the insertion position for type annotations on various * elements. For instance, type annotations for a declaration should be * placed before the type rather than the variable name. */ private static class TypePositionFinder extends TreeScanner<Integer, Void> { private CompilationUnitTree tree; public TypePositionFinder(CompilationUnitTree tree) { super(); this.tree = tree; } /** @param t an expression for a type */ private JCTree leftmostIdentifier(JCTree t) { while (true) { switch (t.getKind()) { case IDENTIFIER: case PRIMITIVE_TYPE: return t; case MEMBER_SELECT: t = ((JCFieldAccess) t).getExpression(); break; case ARRAY_TYPE: t = ((JCArrayTypeTree) t).elemtype; break; case PARAMETERIZED_TYPE: t = ((JCTypeApply) t).getTypeArguments().get(0); break; case EXTENDS_WILDCARD: case SUPER_WILDCARD: t = ((JCWildcard) t).inner; break; case UNBOUNDED_WILDCARD: // This is "?" as in "List<?>". ((JCWildcard) t).inner is null. // There is nowhere to attach the annotation, so for now return // the "?" tree itself. return t; default: throw new RuntimeException(String.format("Unrecognized type (kind=%s, class=%s): %s", t.getKind(), t.getClass(), t)); } } } @Override public Integer visitVariable(VariableTree node, Void p) { JCTree jt = ((JCVariableDecl) node).getType(); if (jt instanceof JCTypeApply) { JCTypeApply vt = (JCTypeApply) jt; return vt.clazz.pos; } JCExpression type = (JCExpression) (((JCVariableDecl)node).getType()); return leftmostIdentifier(type).pos; } // When a method is visited, it is visited for the receiver, not the return value and not the declaration itself. @Override public Integer visitMethod(MethodTree node, Void p) { super.visitMethod(node, p); // System.out.println("node: " + node); // System.out.println("return: " + node.getReturnType()); // location for the receiver annotation int receiverLoc; JCMethodDecl jcnode = (JCMethodDecl) node; List<JCExpression> throwsExpressions = jcnode.thrown; JCBlock body = jcnode.getBody(); List<JCTypeAnnotation> receiverAnnotations = jcnode.receiverAnnotations; if (! throwsExpressions.isEmpty()) { // has a throws expression IdentifierTree it = (IdentifierTree) leftmostIdentifier(throwsExpressions.get(0)); receiverLoc = this.visitIdentifier(it, p); receiverLoc -= 7; // for the 'throws' clause // Search backwards for the close paren. Hope for no problems with // comments. JavaFileObject jfo = tree.getSourceFile(); try { String s = String.valueOf(jfo.getCharContent(true)); for (int i = receiverLoc; i >= 0; i if (s.charAt(i) == ')') { receiverLoc = i + 1; break; } } } catch(IOException e) { throw new RuntimeException(e); } } else if (body != null) { // has a body receiverLoc = body.pos; } else if (! receiverAnnotations.isEmpty()) { // has receiver annotations. After them would be better, but for // now put the new one at the front. receiverLoc = receiverAnnotations.get(0).pos; } else { // try the last parameter, or failing that the return value List<? extends VariableTree> params = jcnode.getParameters(); if (! params.isEmpty()) { VariableTree lastParam = params.get(params.size()-1); receiverLoc = ((JCVariableDecl) lastParam).pos; } else { receiverLoc = jcnode.restype.pos; } // Search forwards for the close paren. Hope for no problems with // comments. JavaFileObject jfo = tree.getSourceFile(); try { String s = String.valueOf(jfo.getCharContent(true)); for (int i = receiverLoc; i < s.length(); i++) { if (s.charAt(i) == ')') { receiverLoc = i + 1; break; } } } catch(IOException e) { throw new RuntimeException(e); } } // TODO: //debugging: System.out.println("result: " + receiverLoc); return receiverLoc; } /** Returns the position of the first bracket at or after the given position. */ // To do: skip over comments private int getFirstBracketAfter(int i) { try { CharSequence s = tree.getSourceFile().getCharContent(true); // return index of first '[' for (int j=i; j < s.length(); j++) { if (s.charAt(j) == '[') { return j; } } } catch(Exception e) { throw new RuntimeException(e); } return i; } private Tree parent(Tree node) { return TreePath.getPath(tree, node).getParentPath().getLeaf(); } @Override public Integer visitIdentifier(IdentifierTree node, Void p) { // for arrays, need to indent inside array, not right before type Tree parent = parent(node); Integer i = null; if (parent instanceof ArrayTypeTree) { debug("TypePositionFinder.visitIdentifier: recognized array"); ArrayTypeTree att = (ArrayTypeTree) parent; JCIdent jcid = (JCIdent) node; i = jcid.pos; } else { i = ((JCIdent) node).pos; } debug("visitId: " + i); return i; } @Override public Integer visitPrimitiveType(PrimitiveTypeTree node, Void p) { // want exact same logistics as with visitIdentifier Tree parent = parent(node); Integer i = null; if (parent instanceof ArrayTypeTree) { ArrayTypeTree att = (ArrayTypeTree) parent; JCTree jcid = (JCTree) node; i = jcid.pos; } else { i = ((JCTree) node).pos; } // JCPrimitiveTypeTree pt = (JCPrimitiveTypeTree) node; JCTree jt = (JCTree) node; return i; } @Override public Integer visitParameterizedType(ParameterizedTypeTree node, Void p) { Tree parent = parent(node); debug("TypePositionFinder.visitParameterizedType %s parent=%s%n", node, parent); Integer i = null; if (parent instanceof ArrayTypeTree) { // want to annotate the first level of this array ArrayTypeTree att = (ArrayTypeTree) parent; Tree baseType = att.getType(); i = leftmostIdentifier(((JCTypeApply) node).getType()).pos; debug("BASE TYPE: " + baseType.toString()); } else { i = leftmostIdentifier(((JCTypeApply)node).getType()).pos; } return i; } // @Override // public Integer visitBlock(BlockTree node, Void p) { // //debugging: System.out.println("visitBlock"); // int rightBeforeBlock = ((JCBlock) node).pos; // // Will be adjusted if a throws statement exists. // int afterParamList = -1; // Tree parent = parent(node); // if (!(methodTree.getKind() == Tree.Kind.METHOD)) { // throw new RuntimeException("BlockTree has non-method parent"); // MethodTree mt = (MethodTree) methodTree; // // TODO: figure out how to better place reciever annotation!!! // // List<? extends VariableTree> vars = mt.getParameters(); // // VariableTree vt = vars.get(0); // // vt.getName().length(); // List<? extends ExpressionTree> throwsExpressions = mt.getThrows(); // if (throwsExpressions.isEmpty()) { // afterParamList = rightBeforeBlock; // } else { // ExpressionTree et = throwsExpressions.get(0); // while (afterParamList == -1) { // switch (et.getKind()) { // case IDENTIFIER: // afterParamList = this.visitIdentifier((IdentifierTree) et, p); // afterParamList -= 7; // for the 'throws' clause // JavaFileObject jfo = tree.getSourceFile(); // try { // String s = String.valueOf(jfo.getCharContent(true)); // for (int i = afterParamList; i >= 0; i--) { // if (s.charAt(i) == ')') { // afterParamList = i + 1; // break; // } catch(IOException e) { // throw new RuntimeException(e); // break; // case MEMBER_SELECT: // et = ((MemberSelectTree) et).getExpression(); // break; // default: // throw new RuntimeException("Unrecognized throws (kind=" + et.getKind() + "): " + et); // // TODO: // //debugging: System.out.println("result: " + afterParamList); // return afterParamList; /** * Returns the number of array levels that are in the given array type tree, * or 0 if the given node is not an array type tree. */ private int arrayLevels(Tree node) { int result = 0; while (node.getKind() == Tree.Kind.ARRAY_TYPE) { result++; node = ((ArrayTypeTree) node).getType(); } return result; } public ArrayTypeTree largestContainingArray(Tree node) { TreePath p = TreePath.getPath(tree, node); Tree result = TreeFinder.largestContainingArray(p).getLeaf(); assert result.getKind() == Tree.Kind.ARRAY_TYPE; return (ArrayTypeTree) result; } private int arrayStartPos(Tree node) { assert node.getKind() == Tree.Kind.ARRAY_TYPE; while (node.getKind() == Tree.Kind.ARRAY_TYPE) { node = ((ArrayTypeTree) node).getType(); } return ((JCTree) node).getPreferredPosition(); } @Override public Integer visitArrayType(ArrayTypeTree node, Void p) { debug("TypePositionFinder.visitArrayType"); JCArrayTypeTree att = (JCArrayTypeTree) node; debug("TypePositionFinder.visitArrayType(%s) preferred = %s%n", node, att.getPreferredPosition()); int pos = arrayStartPos(node); ArrayTypeTree largest = largestContainingArray(node); assert arrayStartPos(node) == pos; int largestLevels = arrayLevels(largest); int levels = arrayLevels(node); pos = getFirstBracketAfter(pos+1); debug(" levels=%d largestLevels=%d%n", levels, largestLevels); for (int i=levels; i<largestLevels; i++) { pos = getFirstBracketAfter(pos+1); debug(" pos %d at i=%d%n", pos, i); } return pos; } @Override public Integer visitCompilationUnit(CompilationUnitTree node, Void p) { JCCompilationUnit cu = (JCCompilationUnit) node; JCTree.JCExpression pid = cu.pid; while (pid instanceof JCTree.JCFieldAccess) { pid = ((JCTree.JCFieldAccess) pid).selected; } JCTree.JCIdent firstComponent = (JCTree.JCIdent) pid; int result = firstComponent.getPreferredPosition(); // Now back up over the word "package" and the preceding newline JavaFileObject jfo = tree.getSourceFile(); String fileContent; try { fileContent = String.valueOf(jfo.getCharContent(true)); } catch(IOException e) { throw new RuntimeException(e); } while (java.lang.Character.isWhitespace(fileContent.charAt(result-1))) { result } result -= 7; String packageString = fileContent.substring(result, result+7); assert "package".equals(packageString) : "expected 'package', got: " + packageString; assert result == 0 || java.lang.Character.isWhitespace(fileContent.charAt(result-1)); return result; } @Override public Integer visitClass(ClassTree node, Void p) { JCClassDecl cd = (JCClassDecl) node; if (cd.mods != null) { return cd.mods.getPreferredPosition(); } else { return cd.getPreferredPosition(); } } } /** * Determine the insertion position for declaration annotations on * various elements. For instance, method declaration annotations should * be placed before all the other modifiers and annotations. */ private static class DeclarationPositionFinder extends TreeScanner<Integer, Void> { private CompilationUnitTree tree; public DeclarationPositionFinder(CompilationUnitTree tree) { super(); this.tree = tree; } // When a method is visited, it is visited for the declaration itself. @Override public Integer visitMethod(MethodTree node, Void p) { super.visitMethod(node, p); // System.out.printf("DeclarationPositionFinder.visitMethod()%n"); ModifiersTree mt = node.getModifiers(); // actually List<JCAnnotation>. List<? extends AnnotationTree> annos = mt.getAnnotations(); Set<Modifier> flags = mt.getFlags(); JCTree before; if (annos.size() > 1) { before = (JCAnnotation) annos.get(0); } else if (node.getReturnType() != null) { before = (JCTree) node.getReturnType(); } else { // if we're a constructor, we have null return type, so we use the constructor's position // rather than the return type's position before = (JCTree) node; } int declPos = TreeInfo.getStartPos(before); // There is no source code location information for Modifiers, so // cannot iterate through the modifiers. But we don't have to. int modsPos = ((JCModifiers)mt).pos().getStartPosition(); if (modsPos != -1) { declPos = Math.min(declPos, modsPos); } return declPos; } @Override public Integer visitCompilationUnit(CompilationUnitTree node, Void p) { JCCompilationUnit cu = (JCCompilationUnit) node; JCTree.JCExpression pid = cu.pid; while (pid instanceof JCTree.JCFieldAccess) { pid = ((JCTree.JCFieldAccess) pid).selected; } JCTree.JCIdent firstComponent = (JCTree.JCIdent) pid; int result = firstComponent.getPreferredPosition(); // Now back up over the word "package" and the preceding newline JavaFileObject jfo = tree.getSourceFile(); String fileContent; try { fileContent = String.valueOf(jfo.getCharContent(true)); } catch(IOException e) { throw new RuntimeException(e); } while (java.lang.Character.isWhitespace(fileContent.charAt(result-1))) { result } result -= 7; String packageString = fileContent.substring(result, result+7); assert "package".equals(packageString) : "expected 'package', got: " + packageString; assert result == 0 || java.lang.Character.isWhitespace(fileContent.charAt(result-1)); return result; } @Override public Integer visitClass(ClassTree node, Void p) { JCClassDecl cd = (JCClassDecl) node; int result; if (cd.mods != null && (cd.mods.flags != 0 || cd.mods.annotations.size() > 0)) { result = cd.mods.getPreferredPosition(); assert result >= 0 : String.format("%d %d %d%n", cd.getStartPosition(), cd.getPreferredPosition(), cd.pos); } else { result = cd.getPreferredPosition(); assert result >= 0 : String.format("%d %d %d%n", cd.getStartPosition(), cd.getPreferredPosition(), cd.pos); } return result; } } /** * A comparator for sorting integers in reverse */ public static class ReverseIntegerComparator implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { return o1.compareTo(o2) * -1; } } private Map<Tree, TreePath> paths; private TypePositionFinder tpf; private DeclarationPositionFinder dpf; private CompilationUnitTree tree; private SetMultimap<Integer, Insertion> positions; // Set of insertions that got added; any insertion not in this set could // not be added. private Set<Insertion> satisfied; /** * Creates a {@code TreeFinder} from a source tree. * * @param tree the source tree to search */ public TreeFinder(CompilationUnitTree tree) { this.tree = tree; this.positions = LinkedHashMultimap.create(); this.tpf = new TypePositionFinder(tree); this.dpf = new DeclarationPositionFinder(tree); this.paths = new HashMap<Tree, TreePath>(); this.satisfied = new HashSet<Insertion>(); } boolean handled(Tree node) { return (node instanceof CompilationUnitTree || node instanceof ClassTree || node instanceof MethodTree || node instanceof VariableTree || node instanceof IdentifierTree || node instanceof ParameterizedTypeTree || node instanceof BlockTree || node instanceof ArrayTypeTree || node instanceof PrimitiveTypeTree); } /** * Scans this tree, using the list of insertions to generate the source * position to insertion text mapping. */ @Override public Void scan(Tree node, List<Insertion> p) { if (node == null) { return null; } if (! handled(node)) { // nothing to do return super.scan(node, p); } TreePath path; if (paths.containsKey(tree)) path = paths.get(tree); else path = TreePath.getPath(tree, node); assert path == null || path.getLeaf() == node : String.format("Mismatch: '%s' '%s' '%s' '%s'%n", path, tree, paths.containsKey(tree), node); // To avoid annotating existing annotations right before // the element you wish to annotate, skip anything inside of // an annotation. if (path != null) { for (Tree t : path) { if (t.getKind() == Tree.Kind.ANNOTATION) { return super.scan(node, p); } } } for (Insertion i : p) { if (satisfied.contains(i)) continue; if (debug) { debug("Considering insertion at tree:"); debug(" " + i); debug(" " + Main.firstLine(node.toString())); } if (!i.getCriteria().isSatisfiedBy(path, node)) { debug(" ... not satisfied"); continue; } else { debug(" ... satisfied!"); } // Question: is this particular annotation already present at this location? // If so, we don't want to insert a duplicate. if (path != null) { ModifiersTree mt = null; if (path != null) { for (Tree n : path) { if (n instanceof ClassTree) { mt = ((ClassTree) n).getModifiers(); break; } else if (n instanceof MethodTree) { mt = ((MethodTree) n).getModifiers(); break; } else if (n instanceof VariableTree) { mt = ((VariableTree) n).getModifiers(); break; } } } // System.out.printf("mt = %s for %s%n", mt, node.getKind()); // printPath(path); if (mt != null) { for (AnnotationTree at : mt.getAnnotations()) { // we compare our to be inserted annotation to the existing annotation, ignoring its // arguments (duplicate annotations are never allowed even if they differ in arguments); // this allows us to skirt around the additional complication that if we did have to // compare our arguments, we'd have to deal with enum arguments potentially being fully // qualified or not: // @Retention(java.lang.annotation.RetentionPolicy.CLASS) vs // @Retention(RetentionPolicy.CLASS) String ann = at.getAnnotationType().toString(); String iann = Main.removeArgs(i.getText()).a.substring(1); // strip off the leading @ String iannNoPackage = Main.removePackage(iann).b; // System.out.printf("Comparing: %s %s %s%n", ann, iann, iannNoPackage); if (ann.equals(iann) || ann.equals(iannNoPackage)) { satisfied.add(i); return super.scan(node, p); } } } } // If this is a method, then it might have been selected because of // the receiver, or because of the return value. Distinguish those. // One way would be to set a global variable here. Another would be // to look for a particular different node. I will do the latter. Integer pos; debug("node: %s%ncritera: %s%n", node, i.getCriteria()); if ((node instanceof MethodTree) && (i.getCriteria().isOnReturnType())) { // looking for the return type pos = tpf.scan(((MethodTree)node).getReturnType(), null); assert handled(node); debug("pos = %d at return type node: %s%n", pos, ((JCMethodDecl)node).getReturnType().getClass()); } else { boolean typeScan = true; if (node instanceof MethodTree) { // looking for the receiver or the declaration typeScan = i.getCriteria().isOnReceiver(); } else if (node instanceof ClassTree) { typeScan = ! i.getSeparateLine(); // hacky check } if (typeScan) { // looking for the type pos = tpf.scan(node, null); assert handled(node); debug("pos = %d at type: %s (%s)%n", pos, node.toString(), node.getClass()); } else { // looking for the declaration pos = dpf.scan(node, null); assert pos != null; debug("pos = %d at declaration: %s%n", pos, node.getClass()); } } debug(" ... satisfied! at %d for node of type %s: %s", pos, node.getClass(), Main.treeToString(node)); if (pos != null) { assert pos >= 0 : String.format("pos: %s%nnode: %s%ninsertion: %s%n", pos, node, i); positions.put(pos, i); } satisfied.add(i); } return super.scan(node, p); } /** * Scans the given tree with the given insertion list and returns the * source position to insertion text mapping. The positions are sorted * in decreasing order of index, so that inserting one doesn't throw * off the index for a subsequent one. * * <p> * <i>N.B.:</i> This method calls {@code scan()} internally. * </p> * * @param node the tree to scan * @param p the list of insertion criteria * @return the source position to insertion text mapping */ public SetMultimap<Integer, Insertion> getPositions(Tree node, List<Insertion> p) { this.scan(node, p); // This needs to be optional, because there may be many extra // annotations in a .jaif file. if (debug) { // Output every insertion that was not given a position: for (Insertion i : p) { if (!satisfied.contains(i) ) { // TODO: && options.hasOption("x")) { System.err.println("Unable to insert: " + i); } } } return Multimaps.unmodifiableSetMultimap(positions); } private static void printPath(TreePath path) { System.out.printf(" if (path != null) { for (Tree t : path) { System.out.printf("%s %s%n", t.getKind(), t); } } System.out.printf(" } }
package com.toomasr.sgf4j.board; import com.toomasr.sgf4j.parser.Util; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; public class BoardCoordinateLabel extends Canvas { private int x; private int y; public BoardCoordinateLabel(int x, int y) { super(BoardSquare.width, BoardSquare.width); this.x = x; this.y = y; init(); } private void init() { GraphicsContext gc = this.getGraphicsContext2D(); // corner square will have an empty string placeholder // if don't put anything then will have alignment issues if ((x == 0 && y == 0) || (x == 20 && y == 20) || (x == 0 && y == 20) || (x == 20 && y == 0)) { gc.fillText(" ", BoardSquare.width / 2 - 0.05 * BoardSquare.width, BoardSquare.width / 2 + 0.3 * BoardSquare.width); } else if (x == 0) { gc.fillText(20-y + "", BoardSquare.width / 2 - 0.15 * BoardSquare.width, BoardSquare.width / 2 + 0.1 * BoardSquare.width); } else if (x == 20) { gc.fillText(20-y + "", 0.15 * BoardSquare.width, BoardSquare.width / 2 + 0.1 * BoardSquare.width); } else if (y == 0) { gc.fillText(Util.alphabet[x - 1], BoardSquare.width / 3, BoardSquare.width / 2 + 0.3 * BoardSquare.width); } else if (y == 20) { gc.fillText(Util.alphabet[x - 1], BoardSquare.width / 3, BoardSquare.width / 3 + 0.2 * BoardSquare.width); } } public void resizeTo(int newSize) { setWidth(newSize); setHeight(newSize); GraphicsContext gc = this.getGraphicsContext2D(); gc.clearRect(0, 0, newSize, newSize); init(); } }
package com.ttaylorr.uhc.pvp.core.gamemodes; import com.ttaylorr.uhc.pvp.PVPManagerPlugin; import com.ttaylorr.uhc.pvp.core.UserManager; import com.ttaylorr.uhc.pvp.util.Continuation; import net.milkbowl.vault.permission.Permission; import nl.dykam.dev.spector.Spector; import org.bukkit.entity.Player; import java.util.HashSet; import java.util.Set; public abstract class GameMode { private Set<Player> players; private PVPManagerPlugin plugin; private Spector spector; private String name; protected abstract void onEnter(Player p); /** * Will cause the player to exit the gamemode. * @param p The player * @param continuation The followup once the player exited the gamemode */ protected abstract void onExit(Player p, Continuation continuation); /** * The supplied player is immediately exited from the gamemode, * regardless of the state he is in. Usually because of unloading etc. * @param p The player */ protected abstract void onImmediateExit(Player p); protected GameMode(PVPManagerPlugin plugin, Spector spector, String name) { this.plugin = plugin; this.spector = spector; this.name = name; players = new HashSet<>(); } public void enter(Player player) { plugin.getDataManager().get(player, UserManager.UserData.class).gameMode = this; players.add(player); Permission permission = plugin.getPermission(); if(permission != null) permission.playerAddGroup(player, "PVPManager-" + name); onEnter(player); spector.assignTo(player); } public void exit(final Player player, final Continuation continuation) { onExit(player, new Continuation(continuation) { @Override public void success() { remove(player); super.success(); } }); } public void immediateExit(Player p) { remove(p); } private void remove(Player p) { players.remove(p); Permission permission = plugin.getPermission(); if(permission != null) permission.playerRemoveGroup(p, "PVPManager-" + name); } public boolean isInGameMode(Player p) { return players.contains(p); } public Iterable<Player> getPlayers() { return players; } public PVPManagerPlugin getPlugin() { return plugin; } }
package net.kyori.adventure.audience; import java.util.Arrays; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collector; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.inventory.Book; import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.SoundStop; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.title.Title; import net.kyori.adventure.title.TitlePart; import org.jetbrains.annotations.NotNull; public interface Audience extends Pointered { /** * Gets an audience that does nothing. * * @return a do-nothing audience * @since 4.0.0 */ static @NotNull Audience empty() { return EmptyAudience.INSTANCE; } /** * Creates an audience that forwards to many other audiences. * * @param audiences an array of audiences, can be empty * @return an audience * @see ForwardingAudience * @since 4.0.0 */ static @NotNull Audience audience(final @NotNull Audience@NotNull... audiences) { final int length = audiences.length; if (length == 0) { return empty(); } else if (length == 1) { return audiences[0]; } return audience(Arrays.asList(audiences)); } /** * Creates an audience that forwards to many other audiences. * * <p>The underlying <code>Iterable</code> is not copied, therefore any changes * made will be reflected in <code>Audience</code>.</p> * * @param audiences an iterable of audiences, can be empty * @return an audience * @see ForwardingAudience * @since 4.0.0 */ static @NotNull ForwardingAudience audience(final @NotNull Iterable<? extends Audience> audiences) { return () -> audiences; } /** * Provides a collector to create a forwarding audience from a stream of audiences. * * <p>The audience produced is immutable and can be reused as desired.</p> * * @return a collector to create a forwarding audience * @since 4.0.0 */ static @NotNull Collector<? super Audience, ?, ForwardingAudience> toAudience() { return Audiences.COLLECTOR; } /** * Filters this audience. * * <p>The returned {@code Audience} may be the same, or a completely different one.</p> * * <p>Container audiences such as {@link ForwardingAudience} may or may not have their own identity. * If they do, they <em>may</em> test themselves against the provided {@code filter} first, and if the test fails return an empty audience skipping any contained children. * If they do not, they <em>must not</em> test themselves against the filter, only testing their children.</p> * * @param filter the filter * @since 4.9.0 */ default @NotNull Audience filterAudience(final @NotNull Predicate<? super Audience> filter) { return filter.test(this) ? this : empty(); } /** * Executes an action against all audiences. * * <p>If you implement {@code Audience} and not {@link ForwardingAudience} in your own code, and your audience forwards to * other audiences, then you <b>must</b> override this method and provide each audience to {@code action}.</p> * * <p>If an implementation of {@code Audience} has its own identity distinct from its contained children, it <em>may</em> test * itself against the provided {@code filter} first, and if the test fails return an empty audience skipping any contained children. * If it does not, it <em>must not</em> test itself against the filter, only testing its children.</p> * * @param action the action * @since 4.9.0 */ default void forEachAudience(final @NotNull Consumer<? super Audience> action) { action.accept(this); } /** * Sends a chat message with a {@link Identity#nil() nil} identity to this {@link Audience}. * * @param message a message * @see Component * @see #sendMessage(Identified, ComponentLike) * @see #sendMessage(Identity, ComponentLike) * @since 4.1.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull ComponentLike message) { this.sendMessage(Identity.nil(), message); } /** * Sends a chat message from the given {@link Identified} to this {@link Audience}. * * @param source the source of the message * @param message a message * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identified source, final @NotNull ComponentLike message) { this.sendMessage(source, message.asComponent()); } /** * Sends a chat message from the entity represented by the given {@link Identity} (or the game using {@link Identity#nil()}) to this {@link Audience}. * * @param source the identity of the source of the message * @param message a message * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identity source, final @NotNull ComponentLike message) { this.sendMessage(source, message.asComponent()); } /** * Sends a chat message with a {@link Identity#nil() nil} identity to this {@link Audience}. * * @param message a message * @see Component * @see #sendMessage(Identified, Component) * @see #sendMessage(Identity, Component) * @since 4.1.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Component message) { this.sendMessage(Identity.nil(), message); } /** * Sends a chat message from the given {@link Identified} to this {@link Audience}. * * @param source the source of the message * @param message a message * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identified source, final @NotNull Component message) { this.sendMessage(source, message, MessageType.SYSTEM); } /** * Sends a chat message from the entity represented by the given {@link Identity} (or the game using {@link Identity#nil()}) to this {@link Audience}. * * @param source the identity of the source of the message * @param message a message * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identity source, final @NotNull Component message) { this.sendMessage(source, message, MessageType.SYSTEM); } /** * Sends a chat message with a {@link Identity#nil() nil} identity to this {@link Audience}. * * @param message a message * @param type the type * @see Component * @see #sendMessage(Identified, ComponentLike, MessageType) * @see #sendMessage(Identity, ComponentLike, MessageType) * @since 4.1.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull ComponentLike message, final @NotNull MessageType type) { this.sendMessage(Identity.nil(), message, type); } /** * Sends a chat message from the given {@link Identified} to this {@link Audience}. * * @param source the source of the message * @param message a message * @param type the type * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identified source, final @NotNull ComponentLike message, final @NotNull MessageType type) { this.sendMessage(source, message.asComponent(), type); } /** * Sends a chat message from the entity represented by the given {@link Identity} (or the game using {@link Identity#nil()}) to this {@link Audience}. * * @param source the identity of the source of the message * @param message a message * @param type the type * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Identity source, final @NotNull ComponentLike message, final @NotNull MessageType type) { this.sendMessage(source, message.asComponent(), type); } /** * Sends a chat message with a {@link Identity#nil() nil} identity to this {@link Audience}. * * @param message a message * @param type the type * @see Component * @see #sendMessage(Identified, Component, MessageType) * @see #sendMessage(Identity, Component, MessageType) * @since 4.1.0 */ @ForwardingAudienceOverrideNotRequired default void sendMessage(final @NotNull Component message, final @NotNull MessageType type) { this.sendMessage(Identity.nil(), message, type); } /** * Sends a chat message. * * @param source the source of the message * @param message a message * @param type the type * @see Component * @since 4.0.0 */ default void sendMessage(final @NotNull Identified source, final @NotNull Component message, final @NotNull MessageType type) { this.sendMessage(source.identity(), message, type); } /** * Sends a chat message. * * @param source the identity of the source of the message * @param message a message * @param type the type * @see Component * @since 4.0.0 */ default void sendMessage(final @NotNull Identity source, final @NotNull Component message, final @NotNull MessageType type) { } /** * Sends a message on the action bar. * * @param message a message * @see Component * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void sendActionBar(final @NotNull ComponentLike message) { this.sendActionBar(message.asComponent()); } /** * Sends a message on the action bar. * * @param message a message * @see Component * @since 4.0.0 */ default void sendActionBar(final @NotNull Component message) { } /** * Sends the player list header. * * <p>Depending on the implementation of this {@code Audience}, an existing footer may be displayed. If you wish * to set both the header and the footer, please use {@link #sendPlayerListHeaderAndFooter(ComponentLike, ComponentLike)}.</p> * * @param header the header * @since 4.3.0 */ @ForwardingAudienceOverrideNotRequired default void sendPlayerListHeader(final @NotNull ComponentLike header) { this.sendPlayerListHeader(header.asComponent()); } /** * Sends the player list header. * * <p>Depending on the implementation of this {@code Audience}, an existing footer may be displayed. If you wish * to set both the header and the footer, please use {@link #sendPlayerListHeaderAndFooter(Component, Component)}.</p> * * @param header the header * @since 4.3.0 */ default void sendPlayerListHeader(final @NotNull Component header) { this.sendPlayerListHeaderAndFooter(header, Component.empty()); } /** * Sends the player list footer. * * <p>Depending on the implementation of this {@code Audience}, an existing footer may be displayed. If you wish * to set both the header and the footer, please use {@link #sendPlayerListHeaderAndFooter(ComponentLike, ComponentLike)}.</p> * * @param footer the footer * @since 4.3.0 */ @ForwardingAudienceOverrideNotRequired default void sendPlayerListFooter(final @NotNull ComponentLike footer) { this.sendPlayerListFooter(footer.asComponent()); } /** * Sends the player list footer. * * <p>Depending on the implementation of this {@code Audience}, an existing footer may be displayed. If you wish * to set both the header and the footer, please use {@link #sendPlayerListHeaderAndFooter(Component, Component)}.</p> * * @param footer the footer * @since 4.3.0 */ default void sendPlayerListFooter(final @NotNull Component footer) { this.sendPlayerListHeaderAndFooter(Component.empty(), footer); } /** * Sends the player list header and footer. * * @param header the header * @param footer the footer * @since 4.3.0 */ @ForwardingAudienceOverrideNotRequired default void sendPlayerListHeaderAndFooter(final @NotNull ComponentLike header, final @NotNull ComponentLike footer) { this.sendPlayerListHeaderAndFooter(header.asComponent(), footer.asComponent()); } /** * Sends the player list header and footer. * * @param header the header * @param footer the footer * @since 4.3.0 */ default void sendPlayerListHeaderAndFooter(final @NotNull Component header, final @NotNull Component footer) { } /** * Shows a title. * * @param title a title * @see Title * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void showTitle(final @NotNull Title title) { this.sendTitlePart(TitlePart.TITLE, title.title()); this.sendTitlePart(TitlePart.SUBTITLE, title.subtitle()); final Title.Times times = title.times(); if (times != null) this.sendTitlePart(TitlePart.TIMES, times); } /** * Shows a part of a title. * * @param part the part * @param value the value * @param <T> the type of the value of the part * @since 4.9.0 */ default <T> void sendTitlePart(final @NotNull TitlePart<T> part, final @NotNull T value) { } /** * Clears the title, if one is being displayed. * * @see Title * @since 4.0.0 */ default void clearTitle() { } /** * Resets the title and timings back to their default. * * @see Title * @since 4.0.0 */ default void resetTitle() { } /** * Shows a boss bar. * * @param bar a boss bar * @see BossBar * @since 4.0.0 */ default void showBossBar(final @NotNull BossBar bar) { } /** * Hides a boss bar. * * @param bar a boss bar * @see BossBar * @since 4.0.0 */ default void hideBossBar(final @NotNull BossBar bar) { } /** * Plays a sound at the location of the recipient of the sound. * * <p>To play a sound that follows the recipient, use {@link #playSound(Sound, Sound.Emitter)} with {@link Sound.Emitter#self()}.</p> * * @param sound a sound * @see Sound * @since 4.0.0 */ default void playSound(final @NotNull Sound sound) { } /** * Plays a sound at a location. * * @param sound a sound * @param x x coordinate * @param y y coordinate * @param z z coordinate * @see Sound * @since 4.0.0 */ default void playSound(final @NotNull Sound sound, final double x, final double y, final double z) { } /** * Stops a sound. * * @param sound the sound * @since 4.8.0 */ @ForwardingAudienceOverrideNotRequired default void stopSound(final @NotNull Sound sound) { this.stopSound(Objects.requireNonNull(sound, "sound").asStop()); } default void playSound(final @NotNull Sound sound, final Sound.@NotNull Emitter emitter) { } /** * Stops a sound, or many sounds. * * @param stop a sound stop * @see SoundStop * @since 4.0.0 */ default void stopSound(final @NotNull SoundStop stop) { } /** * Opens a book. * * <p>When possible, no item should persist after closing the book.</p> * * @param book a book * @see Book * @since 4.0.0 */ @ForwardingAudienceOverrideNotRequired default void openBook(final Book.@NotNull Builder book) { this.openBook(book.build()); } /** * Opens a book. * * <p>When possible, no item should persist after closing the book.</p> * * @param book a book * @see Book * @since 4.0.0 */ default void openBook(final @NotNull Book book) { } }
package com.vaguehope.onosendai.provider; import com.vaguehope.onosendai.provider.successwhale.SuccessWhaleProvider; import com.vaguehope.onosendai.provider.twitter.TwitterProvider; public class ProviderMgr { private final TwitterProvider twitterProvider; private final SuccessWhaleProvider successWhaleProvider; public ProviderMgr () { this.twitterProvider = new TwitterProvider(); this.successWhaleProvider = new SuccessWhaleProvider(); } public TwitterProvider getTwitterProvider () { return this.twitterProvider; } public SuccessWhaleProvider getSuccessWhaleProvider () { return this.successWhaleProvider; } public void shutdown () { try { this.twitterProvider.shutdown(); } finally { this.successWhaleProvider.shutdown(); } } }
package com.webside.ofp.controller; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.disk.DiskFileItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.alibaba.fastjson.JSON; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itextpdf.text.pdf.PdfStructTreeController.returnType; import com.webside.base.basecontroller.BaseController; import com.webside.common.Common; import com.webside.exception.AjaxException; import com.webside.exception.ServiceException; import com.webside.ofp.common.bean.PrintProductTagBean; import com.webside.ofp.common.config.OfpConfig; import com.webside.ofp.common.util.OfpExportUtils; import com.webside.ofp.common.util.PrintUtil; import com.webside.ofp.common.util.StrUtil; import com.webside.ofp.model.ProductEntity; import com.webside.ofp.model.ProductEntityWithBLOBs; import com.webside.ofp.model.ProductTypeEntity; import com.webside.ofp.model.QuotationSheetEntity; import com.webside.ofp.model.QuotationSubSheetEntity; import com.webside.ofp.service.ProductService; import com.webside.ofp.service.ProductTypeService; import com.webside.shiro.ShiroAuthenticationManager; import com.webside.user.model.UserEntity; import com.webside.util.PageUtil; import jodd.util.ArraysUtil; import com.webside.dtgrid.model.Pager; import com.webside.dtgrid.util.ExportUtils; @Controller @Scope("prototype") @RequestMapping(value = "/product/") public class ProductController extends BaseController { @Autowired private ProductService productService; @Autowired private ProductTypeService productTypeService; @RequestMapping("listUI.html") public String listUI(Model model, HttpServletRequest request) { try { List<ProductEntity> list = productService.queryListByPage(new HashMap<String, Object>()); Map<String, Object> parameter = new HashMap<>(); parameter.put("level", 3); List<ProductTypeEntity> productTypeList = productTypeService.queryListAll(parameter); if (!productTypeList.isEmpty()) { model.addAttribute("productTypeChildrenList", productTypeList); } PageUtil page = new PageUtil(); if (request.getParameterMap().containsKey("page")) { page.setPageNum(Integer.valueOf(request.getParameter("page"))); page.setPageSize(Integer.valueOf(request.getParameter("rows"))); page.setOrderByColumn(request.getParameter("sidx")); page.setOrderByType(request.getParameter("sord")); } model.addAttribute("page", page); return Common.BACKGROUND_PATH + "/ofp/product/list"; } catch (Exception e) { throw new AjaxException(e); } } /** * * * @return */ @RequestMapping("listForPrintUI.html") public String listForPrintUI() { return Common.BACKGROUND_PATH + "/ofp/product/listForPrintUI"; } /** * * * @param request * @return * @throws Exception */ @RequestMapping(value = "getAllProducts.html") @ResponseBody public Object getAllProducts(HttpServletRequest request) throws Exception { Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("iTotalRecords", 0); jsonMap.put("iTotalDisplayRecords", 0); List<Map<String, Object>> datas = new ArrayList<>(); datas = productService.selectByPage(jsonMap); jsonMap.put("iTotalRecords", datas.size()); jsonMap.put("iTotalDisplayRecords", datas.size()); jsonMap.put("aaData", datas); return jsonMap; } /** * ajax * * @param dt * Pager * @throws Exception */ @RequestMapping(value = "/list.html", method = RequestMethod.POST) @ResponseBody public Object list(String gridPager, HttpServletResponse response) throws Exception { Map<String, Object> parameters = null; // 1Pager Pager pager = JSON.parseObject(gridPager, Pager.class); parameters = pager.getParameters(); if (parameters.size() < 0) { parameters.put("CN_NAME", null); parameters.put("parentId", null); } /* * UserEntity user = ShiroAuthenticationManager.getUserEntity(); int * roleId = user.getRole().getId().intValue(); parameters.put("roleId", * roleId); */ if (pager.getIsExport()) { if (pager.getExportAllData()) { List<Map<String, Object>> list = productService.selectByPage(parameters); ExportUtils.exportAll(response, pager, list); return null; } else { ExportUtils.export(response, pager); return null; } } else { // page Map<String, Object> map = new HashMap<>(); Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true); List<Map<String, Object>> list = productService.selectByPage(parameters); parameters.clear(); parameters.put("isSuccess", Boolean.TRUE); parameters.put("nowPage", pager.getNowPage()); parameters.put("pageSize", pager.getPageSize()); parameters.put("pageCount", page.getPages()); parameters.put("recordCount", page.getTotal()); parameters.put("startRecord", page.getStartRow()); parameters.put("exhibitDatas", list); return parameters; } } @RequestMapping("addUI.html") public String addUI(Model model) { try { List<ProductEntity> list = productService.queryListByPage(new HashMap<String, Object>()); Map<String, Object> parameter = new HashMap<>(); parameter.put("level", 2); List<ProductTypeEntity> productTypeList = productTypeService.queryListAll(parameter); if (!productTypeList.isEmpty()) { parameter.clear(); model.addAttribute("productTypeList", productTypeList); parameter.put("parentId", productTypeList.get(0).getProductTypeId()); List<ProductTypeEntity> productTypeChildrenList = productTypeService.queryListAll(parameter); if (!productTypeChildrenList.isEmpty()) { model.addAttribute("productTypeChildrenList", productTypeChildrenList); } } return Common.BACKGROUND_PATH + "/ofp/product/form"; } catch (Exception e) { throw new AjaxException(e); } } @RequestMapping("add.html") @ResponseBody public Object add(ProductEntityWithBLOBs productEntityWithBLOBs, ProductTypeEntity productTypeEntity, HttpServletRequest request) throws AjaxException { Map<String, Object> map = new HashMap<String, Object>(); try { StringBuilder sb = this.validateSubmitVal(productEntityWithBLOBs, productTypeEntity); if (sb.length() == 0) { productEntityWithBLOBs.setProductType(productTypeEntity); productEntityWithBLOBs.setIsDelete(0); // cbm=(**)/1000000. double cbm = (productEntityWithBLOBs.getPackHeight() * productEntityWithBLOBs.getWidth() * productEntityWithBLOBs.getLength()) / 1000000; productEntityWithBLOBs.setCbm(cbm); productEntityWithBLOBs.setCreateTime(new Date()); String fileUrl = OfpConfig.exportTempPath + File.separator + productEntityWithBLOBs.getHdMapUrl(); productEntityWithBLOBs.setHdMapUrl(fileUrl); productEntityWithBLOBs.setCreateUser(ShiroAuthenticationManager.getUserId().intValue()); String path = request.getSession().getServletContext().getRealPath("/"); int result = productService.insertWithBlobs(productEntityWithBLOBs, path); if (result == 1) { map.put("success", Boolean.TRUE); map.put("data", null); map.put("message", ""); } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", ""); } } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", "" + sb.toString()); } } catch (ServiceException e) { throw new AjaxException(e); } return map; } /** * * * @param productEntityWithBLOBs * @param productTypeEntity * @return */ private StringBuilder validateSubmitVal(ProductEntityWithBLOBs productEntityWithBLOBs, ProductTypeEntity productTypeEntity) { StringBuilder sb = new StringBuilder(); Map<String, Object> parameter = new HashMap<>(); parameter.put("productCode", productEntityWithBLOBs.getProductCode()); Integer count = productService.count(parameter); if (count > 0) { sb.append(","); } if (productTypeEntity.getProductTypeId() == null) { sb.append(","); } if (StrUtil.noVal(productEntityWithBLOBs.getProductCode())) { sb.append(","); } if (StrUtil.noVal(productEntityWithBLOBs.getProductCode())) { sb.append(","); } if (StrUtil.noVal(productEntityWithBLOBs.getUnit())) { sb.append(","); } if (productEntityWithBLOBs.getUsdPrice() == null || productEntityWithBLOBs.getUsdPrice() <= 0) { sb.append("0,"); } if (StrUtil.noVal(productEntityWithBLOBs.getCnName())) { sb.append(","); } if (productEntityWithBLOBs.getVatRate() == null || productEntityWithBLOBs.getVatRate() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getBuyPrice() == null || productEntityWithBLOBs.getBuyPrice() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getWeight() == null || productEntityWithBLOBs.getWeight() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getVolume() == null || productEntityWithBLOBs.getVolume() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getTop() == null || productEntityWithBLOBs.getTop() <= 0) { sb.append("TOPTOP0,"); } if (productEntityWithBLOBs.getBottom() == null || productEntityWithBLOBs.getBottom() <= 0) { sb.append("BOTTOMBOTTOM0,"); } if (productEntityWithBLOBs.getHeight() == null || productEntityWithBLOBs.getHeight() <= 0) { sb.append("HEIGHTHEIGHT0,"); } if (productEntityWithBLOBs.getLength() == null || productEntityWithBLOBs.getLength() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getWeight() == null || productEntityWithBLOBs.getWeight() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getPackHeight() == null || productEntityWithBLOBs.getPackHeight() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getPackingRate() == null || productEntityWithBLOBs.getPackingRate() <= 0) { sb.append("0,"); } if (productEntityWithBLOBs.getTaxRebateRate() == null || productEntityWithBLOBs.getTaxRebateRate() <= 0) { sb.append("0,"); } /* * if (productEntityWithBLOBs.getCbm() == null || * productEntityWithBLOBs.getCbm() <= 0) { * sb.append("CBMCBM0,"); } */ return sb; } @RequestMapping("editUI.html") public String editUI(Model model, HttpServletRequest request, Long id) { try { ProductEntityWithBLOBs productEntityWithBLOBs = productService.findByIdWithBLOBS(id); Map<String, Object> parameter = new HashMap<>(); parameter.put("level", 2); List<ProductTypeEntity> productTypeList = productTypeService.queryListAll(parameter); if (!productTypeList.isEmpty()) { parameter.clear(); model.addAttribute("productTypeList", productTypeList); parameter.put("parentId", productEntityWithBLOBs.getProductType().getParentId()); List<ProductTypeEntity> productTypeChildrenList = productTypeService.queryListAll(parameter); if (!productTypeChildrenList.isEmpty()) { model.addAttribute("productTypeChildrenList", productTypeChildrenList); } } PageUtil page = new PageUtil(); page.setPageNum(Integer.valueOf(request.getParameter("page"))); page.setPageSize(Integer.valueOf(request.getParameter("rows"))); page.setOrderByColumn(request.getParameter("sidx")); page.setOrderByType(request.getParameter("sord")); model.addAttribute("page", page); model.addAttribute("productEntity", productEntityWithBLOBs); return Common.BACKGROUND_PATH + "/ofp/product/form"; } catch (Exception e) { throw new AjaxException(e); } } @RequestMapping("allList.html") @ResponseBody public Object allList() throws AjaxException { Map<String, Object> map = new HashMap<String, Object>(); try { List<ProductEntity> list = productService.queryListAll(map); if (list != null && list.size() > 0) { map.put("success", Boolean.TRUE); map.put("data", list); map.put("message", ""); } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", ""); } } catch (Exception e) { throw new AjaxException(e); } return map; } /** * * * @param productEntity * @return * @throws AjaxException */ @RequestMapping("getProductTypeChildrenList.html") @ResponseBody public Object getProductTypeChildrenList(ProductTypeEntity productTypeEntity) throws AjaxException { Map<String, Object> map = new HashMap<String, Object>(); try { map.put("parentId", productTypeEntity.getProductTypeId()); List<ProductTypeEntity> productTypeChildrenList = productTypeService.queryListAll(map); if (productTypeChildrenList != null && productTypeChildrenList.size() > 0) { map.put("success", Boolean.TRUE); map.put("data", productTypeChildrenList); map.put("message", ""); } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", ""); } } catch (Exception e) { throw new AjaxException(e); } return map; } @RequestMapping("edit.html") @ResponseBody public Object update(ProductEntityWithBLOBs productEntityWithBLOBs, ProductTypeEntity productTypeEntity, HttpServletRequest request) throws AjaxException { Map<String, Object> map = new HashMap<String, Object>(); try { StringBuilder sb = this.validateSubmitVal(productEntityWithBLOBs, productTypeEntity); if (sb.length() == 0) { productEntityWithBLOBs.setProductType(productTypeEntity); productEntityWithBLOBs.setModifyTime(new Date()); if (productEntityWithBLOBs.getHdMapUrl() != null && productEntityWithBLOBs.getHdMapUrl().indexOf(File.separator) == -1) { String fileUrl = OfpConfig.exportTempPath + File.separator + productEntityWithBLOBs.getHdMapUrl(); productEntityWithBLOBs.setHdMapUrl(fileUrl); } double cbm = (productEntityWithBLOBs.getPackHeight() * productEntityWithBLOBs.getWidth() * productEntityWithBLOBs.getLength()) / 1000000; productEntityWithBLOBs.setCbm(cbm); productEntityWithBLOBs.setModifyUser(ShiroAuthenticationManager.getUserId().intValue()); String path = request.getSession().getServletContext().getRealPath("/"); int result = productService.updateWithBlobs(productEntityWithBLOBs, path); if (result == 1) { map.put("success", Boolean.TRUE); map.put("data", null); map.put("message", ""); } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", ""); } } else { map.put("success", Boolean.FALSE); map.put("data", null); map.put("message", "" + sb.toString()); } } catch (ServiceException e) { throw new AjaxException(e); } return map; } /** * * * @param file * @param request * @param model * @return */ @RequestMapping(value = "uploadPicture.html") @ResponseBody public Object uploadPicture(HttpServletRequest request, ModelMap model) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); Map<String, Object> map = new HashMap<String, Object>(); // request , if (multipartResolver.isMultipart(request)) { try { // String path = System.getProperty("catalina.home"); // request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // request Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null) { String myFileName = UUID.randomUUID().toString() + file.getOriginalFilename(); map.put("data", myFileName); File downloadfile = new File(OfpConfig.exportTempPath); if (!downloadfile.exists()) { downloadfile.mkdirs(); } downloadfile = new File(OfpConfig.exportTempPath + File.separator + myFileName); file.transferTo(downloadfile); // productService.insertWithBlobs(productEntityWithBLOBs, // basePath) } } map.put("success", Boolean.TRUE); map.put("message", ""); } catch (IllegalStateException | IOException e) { map.put("success", Boolean.FALSE); map.put("message", ""); e.printStackTrace(); } } else { map.put("success", Boolean.FALSE); map.put("message", ","); } return map; } @RequestMapping(value = "loadQRCode.html", method = RequestMethod.GET) public void loadQRCode(HttpServletResponse response, @RequestParam("productId") int productId) { OutputStream os = null; try { /** * * * @param response * @param quotationSheet * @param request * @throws Exception */ @RequestMapping(value = "/exportQrCodeBatch.html") public void exportQrCodeBatch(HttpServletResponse response, HttpServletRequest request, String productIds) { String[] productIdArr = productIds.split(","); List<Integer> productIdList = new ArrayList<Integer>(); for (String id : productIdArr) { if (id != null && !"".equals(id)) { productIdList.add(Integer.parseInt(id)); } } try { List<ProductEntityWithBLOBs> productEntityWithBLOBs = productService.findByIdsWithBLOBS(productIdList); OfpExportUtils.exportQrCodeExcel(response, productEntityWithBLOBs); } catch (Exception e) { logger.error("", e); } } /** * * * @param response * @param quotationSheet * @param request * @throws Exception */ @RequestMapping(value = "/printProductTag.html", method = RequestMethod.POST) @ResponseBody public Object printProductTag(HttpServletRequest request, String productIds) throws Exception { String[] productIdArr = productIds.split(","); List<Integer> productIdList = new ArrayList<Integer>(); for (String id : productIdArr) { if (id != null && !"".equals(id)) { productIdList.add(Integer.parseInt(id)); } } Map<String, Object> map = new HashMap<String, Object>(); try { String path = request.getSession().getServletContext().getRealPath("/"); String logoUrl = path + "\\resources\\images\\ofplogo.png"; List<ProductEntityWithBLOBs> productEntityWithBLOBs = productService.findByIdsWithBLOBS(productIdList); List<PrintProductTagBean> productTagBeanlist = new ArrayList<PrintProductTagBean>(); for (ProductEntityWithBLOBs productEntity : productEntityWithBLOBs) { PrintProductTagBean productTagBean = new PrintProductTagBean(); productTagBean.setArtNo("Art No.:" + productEntity.getProductCode()); productTagBean.setFacNo("Fac No.:" + productEntity.getFactoryCode()); productTagBean.setTbh("T/B/H(mm):" + productEntity.getTop() + "*" + productEntity.getBottom() + "*" + productEntity.getHeight()); productTagBean .setWeightAndVol("W(g):" + productEntity.getWeight() + " Vol(ml):" + productEntity.getVolume()); productTagBean.setMeas("Meas.:" + productEntity.getLength() + "*" + productEntity.getWidth() + "*" + productEntity.getPackHeight()); productTagBean.setGw("Gw(kgs).:" + productEntity.getGw()); productTagBean.setQcAndCbm("Q/C:" + productEntity.getPackingRate() + productEntity.getUnit() + " CBM:" + productEntity.getCbm()); productTagBean.setSmallLogo(logoUrl); productTagBeanlist.add(productTagBean); } if (productTagBeanlist.size() > 0) { PrintUtil printUtil = new PrintUtil(productTagBeanlist); int result = printUtil.printContent(); map.put("success", result == 0 ? true : false); } } catch (Exception e) { logger.error("", e); map.put("success", false); } return map; } /** * * * @Description: * @param fileName * @param request * @param response * @return */ @RequestMapping("/downloadfile.html") public String downloadFile(Long productId, HttpServletResponse response) { ProductEntity productEntity = productService.findById(productId); if (productEntity != null) { if (productEntity.getHdMapUrl() != null) { File file = new File(productEntity.getHdMapUrl()); if (file.exists()) { response.setContentType("application/force-download"); String hdMapUrl = productEntity.getHdMapUrl(); String suffix = hdMapUrl.substring(hdMapUrl.lastIndexOf(".")); String fileName = productEntity.getFactoryCode() + suffix; response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } return null; } else { return null; } } }
package joliex.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Map.Entry; import jolie.Interpreter; import jolie.jap.JapURLConnection; import jolie.runtime.AndJarDeps; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import org.ini4j.Ini; /** * * @author Fabrizio Montesi */ @AndJarDeps({"ini4j.jar"}) public class IniUtils extends JavaService { public Value parseIniFile( Value request ) throws FaultException { String filename = request.strValue(); File file = new File( filename ); InputStream istream = null; try { if (file.exists()) { istream = new FileInputStream(file); } else { URL fileURL = interpreter().getClassLoader().findResource( filename ); if (fileURL != null && fileURL.getProtocol().equals("jap")) { URLConnection conn = fileURL.openConnection(); if (conn instanceof JapURLConnection) { JapURLConnection jarConn = (JapURLConnection) conn; istream = jarConn.getInputStream(); } else { throw new FileNotFoundException( filename ); } } else { throw new FileNotFoundException( filename ); } } //Reader reader = new FileReader( istream ); Ini ini = new Ini( istream ); Value response = Value.create(); Value sectionValue; for( Entry< String, Ini.Section > sectionEntry : ini.entrySet() ) { sectionValue = response.getFirstChild( sectionEntry.getKey() ); for( Entry< String, String > entry : sectionEntry.getValue().entrySet() ) { sectionValue.getFirstChild( entry.getKey() ).setValue( entry.getValue() ); } } return response; } catch( IOException e ) { throw new FaultException( "IOException", e ); } finally { try { if ( istream != null ) { istream.close(); } } catch( IOException e ) { Interpreter.getInstance().logWarning( e ); } } } }
package com.yahoo.omid.client.regionserver; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.regionserver.Store; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.serialization.ObjectDecoder; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.yahoo.omid.client.ColumnWrapper; import com.yahoo.omid.tso.messages.MinimumTimestamp; public class Compacter extends BaseRegionObserver { private static final Log LOG = LogFactory.getLog(Compacter.class); private static ExecutorService bossExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder() .setNameFormat("Compacter-Boss-%d").build()); private static ExecutorService workerExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder() .setNameFormat("Compacter-Worker-%d").build()); private volatile long minTimestamp; private ClientBootstrap bootstrap; private ChannelFactory factory; private Channel channel; @Override public void start(CoprocessorEnvironment e) throws IOException { LOG.info("Starting compacter"); Configuration conf = e.getConfiguration(); factory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor, 3); bootstrap = new ClientBootstrap(factory); bootstrap.getPipeline().addLast("decoder", new ObjectDecoder()); bootstrap.getPipeline().addLast("handler", new Handler()); bootstrap.setOption("tcpNoDelay", false); bootstrap.setOption("keepAlive", true); bootstrap.setOption("reuseAddress", true); bootstrap.setOption("connectTimeoutMillis", 100); String host = conf.get("tso.host"); int port = conf.getInt("tso.port", 1234) + 1; if (host == null) { throw new IOException("tso.host missing from configuration"); } bootstrap.connect(new InetSocketAddress(host, port)).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.info("Compacter connected!"); channel = future.getChannel(); } else { LOG.error("Connection failed"); } } }); } @Override public void stop(CoprocessorEnvironment e) throws IOException { LOG.info("Stoping compacter"); if (channel != null) { LOG.info("Calling close"); channel.close(); } LOG.info("Compacter stopped"); } @Override public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, InternalScanner scanner) { if (e.getEnvironment().getRegion().getRegionInfo().isMetaTable()) { return scanner; } else { return new CompacterScanner(scanner, minTimestamp); } } private static class CompacterScanner implements InternalScanner { private InternalScanner internalScanner; private long minTimestamp; private Set<ColumnWrapper> columnsSeen = new HashSet<ColumnWrapper>(); private byte[] lastRowId = null; public CompacterScanner(InternalScanner internalScanner, long minTimestamp) { this.minTimestamp = minTimestamp; this.internalScanner = internalScanner; LOG.info("Created scanner with " + minTimestamp); } @Override public boolean next(List<KeyValue> results) throws IOException { return next(results, -1); } @Override public boolean next(List<KeyValue> result, int limit) throws IOException { boolean moreRows = false; List<KeyValue> raw = new ArrayList<KeyValue>(limit); while (limit == -1 || result.size() < limit) { int toReceive = limit == -1 ? -1 : limit - result.size(); moreRows = internalScanner.next(raw, toReceive); if (raw.size() > 0) { byte[] currentRowId = raw.get(0).getRow(); if (!Arrays.equals(currentRowId, lastRowId)) { columnsSeen.clear(); lastRowId = currentRowId; } } for (KeyValue kv : raw) { ColumnWrapper column = new ColumnWrapper(kv.getFamily(), kv.getQualifier()); if (columnsSeen.add(column) || kv.getTimestamp() > minTimestamp) { result.add(kv); } else if (LOG.isTraceEnabled()){ LOG.trace("Discarded " + kv); } } if (raw.size() < toReceive || toReceive == -1) { columnsSeen.clear(); break; } raw.clear(); } if (!moreRows) { columnsSeen.clear(); } return moreRows; } @Override public void close() throws IOException { internalScanner.close(); } @Override public boolean next(List<KeyValue> results, String metric) throws IOException { return next(results); } @Override public boolean next(List<KeyValue> result, int limit, String metric) throws IOException { return next(result, limit); } } private class Handler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object message = e.getMessage(); if (message instanceof MinimumTimestamp) { Compacter.this.minTimestamp = ((MinimumTimestamp) message).getTimestamp(); } else { LOG.error("Unexpected message: " + message); } } } }
package crazypants.enderio.base.capability; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.common.util.ItemUtil; import com.enderio.core.common.util.NNList; import com.enderio.core.common.util.NullHelper; import crazypants.enderio.base.machine.base.te.AbstractMachineEntity; import crazypants.enderio.base.machine.modes.IoMode; import crazypants.enderio.util.Prep; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; public class ItemTools { @CapabilityInject(IItemHandler.class) public static Capability<IItemHandler> ITEM_HANDLER_CAPABILITY = null; private ItemTools() { } public static boolean doPush(@Nonnull final IBlockAccess world, @Nonnull final BlockPos pos) { final CallbackPush callback = new CallbackPush(world, pos); NNList.FACING.apply(callback); return callback.movedSomething; } private static final class CallbackPush implements NNList.ShortCallback<EnumFacing> { private final @Nonnull IBlockAccess world; private final @Nonnull BlockPos pos; boolean movedSomething = false; private CallbackPush(@Nonnull IBlockAccess world, @Nonnull BlockPos pos) { this.world = world; this.pos = pos; } @Override public boolean apply(@Nonnull EnumFacing facing) { MoveResult moveResult = move(NO_LIMIT, world, pos, facing, pos.offset(facing), facing.getOpposite()); if (moveResult == MoveResult.SOURCE_EMPTY) { return true; } movedSomething |= moveResult == MoveResult.MOVED; return false; } } public static boolean doPull(@Nonnull IBlockAccess world, @Nonnull BlockPos pos) { final CallbackPull callback = new CallbackPull(world, pos); NNList.FACING.apply(callback); return callback.movedSomething; } private static final class CallbackPull implements NNList.ShortCallback<EnumFacing> { private final @Nonnull IBlockAccess world; private final @Nonnull BlockPos pos; boolean movedSomething = false; private CallbackPull(@Nonnull IBlockAccess world, @Nonnull BlockPos pos) { this.world = world; this.pos = pos; } @Override public boolean apply(@Nonnull EnumFacing facing) { MoveResult moveResult = move(NO_LIMIT, world, pos.offset(facing), facing.getOpposite(), pos, facing); if (moveResult == MoveResult.TARGET_FULL) { return true; } movedSomething |= moveResult == MoveResult.MOVED; return false; } } public static enum MoveResult { NO_ACTION, LIMITED, MOVED, TARGET_FULL, SOURCE_EMPTY; } public static MoveResult move(@Nonnull Limit limit, @Nonnull IBlockAccess world, @Nonnull BlockPos sourcePos, @Nonnull EnumFacing sourceFacing, @Nonnull BlockPos targetPos, @Nonnull EnumFacing targetFacing) { if (!limit.canWork()) { return MoveResult.LIMITED; } boolean movedSomething = false; TileEntity source = world.getTileEntity(sourcePos); if (source != null && source.hasWorld() && !source.getWorld().isRemote && canPullFrom(source, sourceFacing)) { TileEntity target = world.getTileEntity(targetPos); if (target != null && target.hasWorld() && canPutInto(target, targetFacing)) { IItemHandler sourceHandler = getExternalInventory(world, sourcePos, sourceFacing); if (sourceHandler != null && hasItems(sourceHandler)) { IItemHandler targetHandler = getExternalInventory(world, targetPos, targetFacing); if (targetHandler != null && hasFreeSpace(targetHandler)) { for (int i = 0; i < sourceHandler.getSlots(); i++) { ItemStack removable = sourceHandler.extractItem(i, limit.getItems(), true); if (Prep.isValid(removable)) { ItemStack unacceptable = ItemHandlerHelper.insertItemStacked(targetHandler, removable, true); int movable = removable.getCount() - unacceptable.getCount(); if (movable > 0) { ItemStack removed = sourceHandler.extractItem(i, movable, false); if (Prep.isValid(removed)) { ItemStack targetRejected = ItemHandlerHelper.insertItemStacked(targetHandler, removed, false); if (Prep.isValid(targetRejected)) { ItemStack sourceRejected = ItemHandlerHelper.insertItemStacked(sourceHandler, targetRejected, false); if (Prep.isValid(sourceRejected)) { EntityItem drop = new EntityItem(source.getWorld(), sourcePos.getX() + 0.5, sourcePos.getY() + 0.5, sourcePos.getZ() + 0.5, sourceRejected); source.getWorld().spawnEntity(drop); return MoveResult.MOVED; } } } movedSomething = true; limit.useItems(movable); if (!limit.canWork()) { return MoveResult.MOVED; } } } } } else { return MoveResult.TARGET_FULL; } } else { return MoveResult.SOURCE_EMPTY; } } else { return MoveResult.TARGET_FULL; } } else { return MoveResult.SOURCE_EMPTY; } return movedSomething ? MoveResult.MOVED : MoveResult.NO_ACTION; } /** * * @param inventory * @param item * @return the number inserted */ public static int doInsertItem(@Nullable IItemHandler inventory, @Nonnull ItemStack item) { if (inventory == null || Prep.isInvalid(item)) { return 0; } int startSize = item.getCount(); ItemStack res = ItemHandlerHelper.insertItemStacked(inventory, item.copy(), false); int val = startSize - res.getCount(); return val; } public static boolean hasFreeSpace(@Nonnull IItemHandler handler) { for (int i = 0; i < handler.getSlots(); i++) { ItemStack stack = handler.getStackInSlot(i); if (Prep.isInvalid(stack) || (stack.isStackable() && stack.getCount() < stack.getMaxStackSize() && stack.getCount() < handler.getSlotLimit(i))) { return true; } } return false; } public static boolean hasItems(@Nonnull IItemHandler handler) { for (int i = 0; i < handler.getSlots(); i++) { ItemStack stack = handler.getStackInSlot(i); if (Prep.isValid(stack)) { return true; } } return false; } public static int countItems(@Nonnull IItemHandler handler, @Nonnull ItemStack template) { int count = 0; for (int i = 0; i < handler.getSlots(); i++) { ItemStack stack = handler.getStackInSlot(i); if (ItemUtil.areStacksEqual(template, stack)) { count += stack.getCount(); } } return count; } /** * Determines how many items can be inserted into an inventory given that the number of items is limited by "limit". * * @param handler * The target inventory * @param template * The item to insert * @param limit * The limit, meaning the maximum number of items that are allowed in the inventory. * @return The number of items that can be inserted without violating the limit. */ public static int getInsertLimit(@Nonnull IItemHandler handler, @Nonnull ItemStack template, int limit) { int count = 0; for (int i = 0; i < handler.getSlots(); i++) { ItemStack stack = handler.getStackInSlot(i); if (ItemUtil.areStacksEqual(template, stack)) { count += stack.getCount(); } if (count >= limit) { return 0; } } return limit - count; } public static boolean hasAtLeast(@Nonnull IItemHandler handler, @Nonnull ItemStack template, int limit) { int count = 0; for (int i = 0; i < handler.getSlots(); i++) { ItemStack stack = handler.getStackInSlot(i); if (com.enderio.core.common.util.ItemUtil.areStacksEqual(template, stack)) { count += stack.getCount(); } if (count >= limit) { return true; } } return false; } public static boolean canPutInto(@Nullable TileEntity tileEntity, @Nonnull EnumFacing facing) { if (tileEntity instanceof AbstractMachineEntity) { IoMode ioMode = ((AbstractMachineEntity) tileEntity).getIoMode(facing); return ioMode != IoMode.DISABLED && ioMode != IoMode.PUSH; } return true; } public static boolean canPullFrom(@Nullable TileEntity tileEntity, @Nonnull EnumFacing facing) { if (tileEntity instanceof AbstractMachineEntity) { IoMode ioMode = ((AbstractMachineEntity) tileEntity).getIoMode(facing); return ioMode != IoMode.DISABLED && ioMode != IoMode.PULL; } return true; } public static final @Nonnull Limit NO_LIMIT = new Limit(Integer.MAX_VALUE, Integer.MAX_VALUE) { @Override public void useItems(int count) { } }; public static class Limit { private int stacks, items; public Limit(int stacks, int items) { this.stacks = stacks; this.items = items; } public Limit(int items) { this.stacks = Integer.MAX_VALUE; this.items = items; } public int getStacks() { return stacks; } public int getItems() { return items; } public void useItems(int count) { stacks items -= count; } public boolean canWork() { return stacks > 0 && items > 0; } public @Nonnull Limit copy() { return new Limit(stacks, items); } } public static @Nullable IItemHandler getExternalInventory(@Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nonnull EnumFacing face) { TileEntity te = world.getTileEntity(pos); if (te != null) { return getExternalInventory(te, face); } return null; } public static @Nullable IItemHandler getExternalInventory(@Nonnull TileEntity tile, @Nonnull EnumFacing face) { return tile.getCapability(NullHelper.notnullF(ITEM_HANDLER_CAPABILITY, "Capability<IItemHandler> is missing"), face); } }
package de.domisum.lib.auxilium.util.java; import de.domisum.lib.auxilium.util.java.annotations.API; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ThreadUtil { private static final Logger LOGGER = LoggerFactory.getLogger("threadUtil"); @API public static boolean sleep(long ms) { try { Thread.sleep(ms); return true; } catch(InterruptedException ignored) { Thread.currentThread().interrupt(); return false; } } @API public static boolean join(Thread thread) { try { thread.join(); return true; } catch(InterruptedException ignored) { Thread.currentThread().interrupt(); return false; } } @API public static boolean wait(Object object) { try { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(object) { object.wait(); } return true; } catch(InterruptedException ignored) { return false; } } @API public static void notifyAll(Object object) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(object) { object.notifyAll(); } } @API public static Thread createThread(Runnable runnable, String threadName) { Thread thread = new Thread(runnable); thread.setName(threadName); logUncaughtExceptions(thread); return thread; } @API public static Thread createAndStartThread(Runnable runnable, String threadName) { Thread thread = createThread(runnable, threadName); thread.start(); return thread; } @API public static Thread runDelayed(Runnable run, long ms) { Runnable delayed = ()-> { sleep(ms); run.run(); }; return createAndStartThread(delayed, "delayedTask"); } @API public static void addShutdownHook(Runnable shutdownHook) { addShutdownHook(shutdownHook, "shutdownHook"); } @API public static void addShutdownHook(Runnable shutdownHook, String shutdownHookName) { Thread shutdownHookThread = createThread(shutdownHook, shutdownHookName); Runtime.getRuntime().addShutdownHook(shutdownHookThread); } @API public static void logUncaughtExceptions(Thread thread) { thread.setUncaughtExceptionHandler((t, e)->LOGGER.error("uncaught exception in thread {}", t, e)); } }
package de.domisum.lib.auxilium.util.math; import de.domisum.lib.auxilium.data.container.math.Vector3D; import de.domisum.lib.auxilium.util.java.annotations.APIUsage; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; @APIUsage public class RandomUtil { // REFERENCES private static Random random; // basic @APIUsage public static Random getRandom() { if(random == null) random = new Random(); return random; } @APIUsage public static int nextInt(int bound) { return nextInt(bound, getRandom()); } @APIUsage public static int nextInt(int bound, Random r) { return r.nextInt(bound); } @APIUsage public static double nextDouble() { return nextDouble(getRandom()); } @APIUsage public static double nextDouble(Random r) { return r.nextDouble(); } @APIUsage public static boolean nextBoolean() { return nextBoolean(getRandom()); } @APIUsage public static boolean nextBoolean(Random r) { return r.nextBoolean(); } // number @APIUsage public static double distribute(double base, double maxDifference) { return distribute(base, maxDifference, getRandom()); } @APIUsage public static double distribute(double base, double maxDifference, Random r) { return base+((r.nextBoolean() ? 1 : -1)*r.nextDouble()*maxDifference); } @APIUsage public static int distribute(int base, int maxDifference) { return distribute(base, maxDifference, getRandom()); } @APIUsage public static int distribute(int base, int maxDifference, Random r) { return (int) Math.round(distribute((double) base, maxDifference, r)); // cast to double so it picks the double method } @APIUsage public static int getFromRange(int min, int max) { return getFromRange(min, max, getRandom()); } @APIUsage public static int getFromRange(int min, int max, Random r) { return min+(nextInt((max-min)+1, r)); } @APIUsage public static double getFromRange(double min, double max) { return getFromRange(min, max, getRandom()); } @APIUsage public static double getFromRange(double min, double max, Random r) { return min+nextDouble(r)*(max-min); } // vector @APIUsage public static Vector3D getUnitVector() { return getUnitVector(RandomUtil.getRandom()); } @APIUsage public static Vector3D getUnitVector(Random random) { double theta = random.nextDouble()*2*Math.PI; double r = (random.nextDouble()*2)-1; double rootComponent = Math.sqrt(1-(r*r)); double x = rootComponent*Math.cos(theta); double y = rootComponent*Math.sin(theta); return new Vector3D(x, y, r); } // random element @APIUsage public static <E> E getElement(List<E> list) { return getElement(list, getRandom()); } @APIUsage public static <E> E getElement(List<E> list, Random r) { if(list.size() == 0) throw new IllegalArgumentException("The list has to have at least 1 element"); int randomIndex = getFromRange(0, list.size()-1, r); return list.get(randomIndex); } @APIUsage public static <E> E getElement(Collection<E> coll) { return getElement(coll, getRandom()); } @APIUsage public static <E> E getElement(Collection<E> coll, Random r) { if(coll.size() == 0) throw new IllegalArgumentException("The collection has to have at least 1 element"); int randomIndex = getFromRange(0, coll.size()-1, r); Iterator<E> iterator = coll.iterator(); E latestElement = null; for(int i = 0; i <= randomIndex; i++) latestElement = iterator.next(); return latestElement; } @APIUsage public static <E> E getElement(E[] array) { return getElement(array, getRandom()); } @APIUsage public static <E> E getElement(E[] array, Random r) { if(array.length == 0) throw new IllegalArgumentException("The array has to have at least 1 element"); int randomIndex = getFromRange(0, array.length-1, r); return array[randomIndex]; } }
/* * Converter.java * */ package de.uni_stuttgart.vis.vowl.owl2vowl; import de.uni_stuttgart.vis.vowl.owl2vowl.export.Exporter; import de.uni_stuttgart.vis.vowl.owl2vowl.export.JsonGenerator; import de.uni_stuttgart.vis.vowl.owl2vowl.model.OntologyMetric; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.GeneralParser; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.ProcessUnit; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.MapData; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.OntologyInformation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.metrics.*; import org.semanticweb.owlapi.model.*; import java.util.Collections; import java.util.List; import java.util.Set; /** * The {@link de.uni_stuttgart.vis.vowl.owl2vowl.Converter} loads the passed ontologies and has * methods to start the conversion and the export. */ public class Converter { private static final Logger logger = LogManager.getRootLogger(); private static MapData mapData; private final JsonGenerator jsonGenerator = new JsonGenerator(); private OntologyInformation ontologyInformation; private OWLOntologyManager ontologyManager; private OWLOntology ontology; private OWLDataFactory dataFactory; public Converter(IRI ontologyIRI) throws OWLOntologyCreationException { this(ontologyIRI, Collections.<IRI>emptyList()); } public Converter(IRI ontologyIRI, List<IRI> necessaryExternals) throws OWLOntologyCreationException { initializeAPI(); logger.info("Loading ontologies ... [" + ontologyIRI + ", " + necessaryExternals + "]"); if (!necessaryExternals.isEmpty()) { for (IRI externalIRI : necessaryExternals) { ontologyManager.loadOntology(externalIRI); } logger.info("External ontologies loaded!"); } ontology = ontologyManager.loadOntology(ontologyIRI); String logOntoName = ontologyIRI.toString(); ontologyInformation = new OntologyInformation(ontology, ontologyIRI); if (!ontology.isAnonymous()) { logOntoName = ontology.getOntologyID().getOntologyIRI().getFragment(); } else { logger.info("Ontology IRI is anonymous. Use loaded URI/IRI instead."); } logger.info("Ontologies loaded! Main Ontology: " + logOntoName); } private void initializeAPI() { logger.info("Initializing OWL API ..."); ontologyManager = OWLManager.createOWLOntologyManager(); dataFactory = ontologyManager.getOWLDataFactory(); logger.info("OWL API initialized!"); } public void convert() { mapData = new MapData(); Set<OWLClass> classes = ontology.getClassesInSignature(); Set<OWLDatatype> datatypes = ontology.getDatatypesInSignature(); Set<OWLObjectProperty> objectProperties = ontology.getObjectPropertiesInSignature(); Set<OWLDataProperty> dataProperties = ontology.getDataPropertiesInSignature(); ProcessUnit processor = new ProcessUnit(ontologyInformation, mapData); GeneralParser parser = new GeneralParser(ontologyInformation, mapData); /* Parsing of the raw data gained from the OWL API. Will be transformed to useable data for WebVOWL. */ parser.handleOntologyInfo(); parser.handleClass(classes); processor.processClasses(); //parseDatatypes(datatypes); parser.handleObjectProperty(objectProperties); parser.handleDatatypeProperty(dataProperties); parseMetrics(); //processor.processDatatypes(); processor.processProperties(); processor.processAxioms(); } public void export(Exporter exporter) throws Exception { jsonGenerator.execute(mapData); jsonGenerator.export(exporter); } /** * Save the metrics of the current loaded ontology. * TODO Should be optimized probalby... */ public void parseMetrics() { OntologyMetric ontologyMetric = mapData.getOntologyMetric(); OWLMetric metric = new ReferencedClassCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setClassCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedObjectPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setObjectPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedDataPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setDataPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedIndividualCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setIndividualCount(Integer.parseInt(metric.getValue().toString())); metric = new AxiomCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setAxiomCount(Integer.parseInt(metric.getValue().toString())); // metric = new DLExpressivity(ontology.getOWLOntologyManager()); // metric.setOntology(ontology); ontologyMetric.calculateSums(); } public IRI getOntologyIri() { return ontology.getOntologyID().getOntologyIRI(); } }
package edu.harvard.iq.dataverse.dataset; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.GetRequest; import edu.harvard.iq.dataverse.DataFile; import edu.harvard.iq.dataverse.Dataset; import edu.harvard.iq.dataverse.FileMetadata; import edu.harvard.iq.dataverse.dataaccess.ImageThumbConverter; import edu.harvard.iq.dataverse.util.FileUtil; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Base64; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; public class DatasetUtil { private static final Logger logger = Logger.getLogger(DatasetUtil.class.getCanonicalName()); public static String datasetLogoFilenameFinal = "dataset_logo_original"; public static String datasetLogoThumbnail = "dataset_logo"; public static String thumb48addedByImageThumbConverter = ".thumb48"; public static List<DatasetThumbnail> getThumbnailCandidates(Dataset dataset, boolean considerDatasetLogoAsCandidate) { List<DatasetThumbnail> thumbnails = new ArrayList<>(); if (dataset == null) { return thumbnails; } if (considerDatasetLogoAsCandidate) { Path path = Paths.get(dataset.getFileSystemDirectory() + File.separator + datasetLogoThumbnail + thumb48addedByImageThumbConverter); if (Files.exists(path)) { logger.fine("Thumbnail created from dataset logo exists!"); File file = path.toFile(); try { byte[] bytes = Files.readAllBytes(file.toPath()); String base64image = Base64.getEncoder().encodeToString(bytes); DatasetThumbnail datasetThumbnail = new DatasetThumbnail(FileUtil.DATA_URI_SCHEME + base64image, null); thumbnails.add(datasetThumbnail); } catch (IOException ex) { logger.info("Unable to rescale image: " + ex); } } else { logger.fine("There is no thumbnail created from a dataset logo"); } } for (FileMetadata fileMetadata : dataset.getLatestVersion().getFileMetadatas()) { DataFile dataFile = fileMetadata.getDataFile(); if (dataFile != null && dataFile.isImage() && !dataFile.isRestricted()) { String imageSourceBase64 = ImageThumbConverter.getImageThumbAsBase64(dataFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE); DatasetThumbnail datasetThumbnail = new DatasetThumbnail(imageSourceBase64, dataFile); thumbnails.add(datasetThumbnail); } } return thumbnails; } public static DatasetThumbnail getThumbnail(Dataset dataset) { if (dataset == null) { return null; } String title = dataset.getLatestVersion().getTitle(); Path path = Paths.get(dataset.getFileSystemDirectory() + File.separator + datasetLogoThumbnail + thumb48addedByImageThumbConverter); if (Files.exists(path)) { try { byte[] bytes = Files.readAllBytes(path); String base64image = Base64.getEncoder().encodeToString(bytes); DatasetThumbnail datasetThumbnail = new DatasetThumbnail(FileUtil.DATA_URI_SCHEME + base64image, null); logger.fine(title + " will get thumbnail from dataset logo."); return datasetThumbnail; } catch (IOException ex) { logger.fine("Unable to rescale image: " + ex); return null; } } else { DataFile thumbnailFile = dataset.getThumbnailFile(); if (thumbnailFile == null) { if (dataset.isUseGenericThumbnail()) { logger.fine(title + " does not have a thumbnail and is 'Use Generic'."); return null; } else { thumbnailFile = dataset.getDefaultDatasetThumbnailFile(); if (thumbnailFile == null) { logger.fine(title + " does not have a default thumbnail available."); return null; } else { String imageSourceBase64 = ImageThumbConverter.getImageThumbAsBase64(thumbnailFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE); DatasetThumbnail defaultDatasetThumbnail = new DatasetThumbnail(imageSourceBase64, thumbnailFile); logger.fine(title + " will get thumbnail through automatic selection from DataFile id " + thumbnailFile.getId()); return defaultDatasetThumbnail; } } } else if (thumbnailFile.isRestricted()) { logger.fine(title + " has a thumbnail the user selected but the file must have later been restricted. Returning null."); return null; } else { String imageSourceBase64 = ImageThumbConverter.getImageThumbAsBase64(thumbnailFile, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE); DatasetThumbnail userSpecifiedDatasetThumbnail = new DatasetThumbnail(imageSourceBase64, thumbnailFile); logger.fine(title + " will get thumbnail the user specified from DataFile id " + thumbnailFile.getId()); return userSpecifiedDatasetThumbnail; } } } public static boolean deleteDatasetLogo(Dataset dataset) { if (dataset == null) { return false; } File originalFile = new File(dataset.getFileSystemDirectory().toString(), datasetLogoFilenameFinal); boolean originalFileDeleted = originalFile.delete(); File thumb48 = new File(dataset.getFileSystemDirectory().toString(), File.separator + datasetLogoThumbnail + thumb48addedByImageThumbConverter); boolean thumb48Deleted = thumb48.delete(); if (originalFileDeleted && thumb48Deleted) { return true; } else { logger.info("One of the files wasn't deleted. Original deleted: " + originalFileDeleted + ". thumb48 deleted: " + thumb48Deleted + "."); return false; } } public static DataFile getDefaultThumbnailFile(Dataset dataset) { if (dataset == null) { return null; } if (dataset.isUseGenericThumbnail()) { logger.fine("Bypassing logic to find a thumbnail because a generic icon for the dataset is desired."); return null; } for (FileMetadata fmd : dataset.getLatestVersion().getFileMetadatas()) { DataFile testFile = fmd.getDataFile(); if (testFile.isPreviewImageAvailable() && !testFile.isRestricted()) { return testFile; } } return null; } public static Dataset persistDatasetLogoToDiskAndCreateThumbnail(Dataset dataset, InputStream inputStream) { if (dataset == null) { return null; } File tmpFile = null; try { tmpFile = FileUtil.inputStreamToFile(inputStream); } catch (IOException ex) { Logger.getLogger(DatasetUtil.class.getName()).log(Level.SEVERE, null, ex); } Path datasetDirectory = dataset.getFileSystemDirectory(); if (datasetDirectory != null && !Files.exists(datasetDirectory)) { try { Files.createDirectories(datasetDirectory); } catch (IOException ex) { Logger.getLogger(ImageThumbConverter.class.getName()).log(Level.SEVERE, null, ex); logger.info("Dataset directory " + datasetDirectory + " does not exist but couldn't create it. Exception: " + ex); return null; } } File originalFile = new File(datasetDirectory.toString(), datasetLogoFilenameFinal); try { Files.copy(tmpFile.toPath(), originalFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { logger.severe("Failed to original file from " + tmpFile.getAbsolutePath() + " to " + originalFile.getAbsolutePath() + ": " + ex); } String fileLocation = dataset.getFileSystemDirectory() + File.separator + datasetLogoThumbnail; BufferedImage fullSizeImage = null; try { fullSizeImage = ImageIO.read(originalFile); } catch (IOException ex) { Logger.getLogger(ImageThumbConverter.class.getName()).log(Level.SEVERE, null, ex); return null; } if (fullSizeImage == null) { logger.fine("fullSizeImage was null!"); return null; } int width = fullSizeImage.getWidth(); int height = fullSizeImage.getHeight(); FileChannel src = null; try { src = new FileInputStream(originalFile).getChannel(); } catch (FileNotFoundException ex) { Logger.getLogger(ImageThumbConverter.class.getName()).log(Level.SEVERE, null, ex); return null; } FileChannel dest = null; try { dest = new FileOutputStream(originalFile).getChannel(); } catch (FileNotFoundException ex) { Logger.getLogger(ImageThumbConverter.class.getName()).log(Level.SEVERE, null, ex); return null; } try { dest.transferFrom(src, 0, src.size()); } catch (IOException ex) { Logger.getLogger(ImageThumbConverter.class.getName()).log(Level.SEVERE, null, ex); return null; } String thumbFileLocation = ImageThumbConverter.rescaleImage(fullSizeImage, width, height, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE, fileLocation); boolean originalFileWasDeleted = originalFile.delete(); logger.fine("Thumbnail saved to " + thumbFileLocation + ". Original file was deleted: " + originalFileWasDeleted); return dataset; } public static String getThumbnailImageString(String siteUrl, Long datasetId) { /** * Calls getThumbnailAsInputStream via API then converts to image * string. Allows SolrSearchResult to get image w/o having dataset in * hand. */ String unirestUrlForThumbAPI = siteUrl + "/api/datasets/" + datasetId + "/thumbnail"; logger.fine("In getThumbnailImageString and about to operation on this URL: " + unirestUrlForThumbAPI); GetRequest unirestOut = Unirest.get(unirestUrlForThumbAPI); InputStream unirestInputStream = null; try { unirestInputStream = unirestOut.asBinary().getBody(); } catch (UnirestException ex) { logger.info("UnirestException caught attempting to GET " + unirestUrlForThumbAPI + " and exception was: " + ex); return null; } if (unirestInputStream == null) { return null; } try { byte[] bytes = IOUtils.toByteArray(unirestInputStream); String base64image = Base64.getEncoder().encodeToString(bytes); DatasetThumbnail datasetThumbnail = new DatasetThumbnail(FileUtil.DATA_URI_SCHEME + base64image, null); return datasetThumbnail.getBase64image(); } catch (IOException e) { logger.fine("input Stream could not be converted to Image String for dataset id " + datasetId); } return null; } public static InputStream getThumbnailAsInputStream(Dataset dataset) { if (dataset == null) { return null; } DatasetThumbnail datasetThumbnail = dataset.getDatasetThumbnail(); if (datasetThumbnail == null) { return null; } else { String base64Image = datasetThumbnail.getBase64image(); String leadingStringToRemove = FileUtil.DATA_URI_SCHEME; String encodedImg = base64Image.substring(leadingStringToRemove.length()); byte[] decodedImg = null; try { decodedImg = Base64.getDecoder().decode(encodedImg.getBytes("UTF-8")); logger.fine("returning this many bytes for " + "dataset id: " + dataset.getId() + ", persistentId: " + dataset.getIdentifier() + " :" + decodedImg.length); } catch (UnsupportedEncodingException ex) { logger.info("dataset thumbnail could not be decoded for dataset id " + dataset.getId() + ": " + ex); return null; } ByteArrayInputStream nonDefaultDatasetThumbnail = new ByteArrayInputStream(decodedImg); logger.fine("For dataset id " + dataset.getId() + " a thumbnail was found and is being returned."); return nonDefaultDatasetThumbnail; } } /** * The dataset logo is the file that a user uploads which is *not* one of * the data files. Compare to the datavese logo. We do not save the original * file that is uploaded. Rather, we delete it after first creating at least * one thumbnail from it. */ public static boolean isDatasetLogoPresent(Dataset dataset) { if (dataset == null) { return false; } return Files.exists(Paths.get(dataset.getFileSystemDirectory() + File.separator + datasetLogoFilenameFinal)); } }
package edu.umass.ciir.galagotools.scoring; import edu.umass.ciir.galagotools.utils.Util; import org.lemurproject.galago.core.retrieval.iterator.BaseIterator; import org.lemurproject.galago.core.retrieval.traversal.Traversal; import org.lemurproject.galago.utility.Parameters; /** * @author jfoley. */ public class IterUtils { public static void addToParameters(Parameters p, String name, Class<? extends BaseIterator> iterClass) { if(!p.containsKey("operators")) { p.put("operators", Parameters.instance()); } p.getMap("operators").put(name, iterClass.getName()); } public static void addToParameters(Parameters argp, Class<? extends Traversal> traversalClass) { Util.extendList(argp, "traversals", Parameters.class, Parameters.parseArray( "name", traversalClass.getName() )); } }
package edu.wright.hendrix11.familyTree.entity; import edu.wright.hendrix11.familyTree.entity.event.Event; import java.util.Date; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Joe Hendrix <hendrix.11@wright.edu> */ @Entity public class Birth implements Event { @Id @Column(name = "PERSON_ID") private int id; @OneToOne @PrimaryKeyJoinColumn private Person person; @ManyToOne @JoinColumn(name="PLACE_ID") private String place; @Temporal(TemporalType.DATE) private Date date; @Override public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override public Person getPerson() { return person; } @Override public void setPerson(Person person) { this.person = person; } @Override public String getPlace() { return place; } @Override public void setPlace(String place) { this.place = place; } @Override public Date getDate() { return date; } @Override public void setDate(Date date) { this.date = date; } }
package eu.musesproject.server.rt2ae; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import javax.persistence.EntityTransaction; import org.apache.log4j.Logger; import eu.musesproject.server.db.handler.DBManager; import eu.musesproject.server.entity.RiskPolicy; import eu.musesproject.server.eventprocessor.correlator.model.owl.ConnectivityEvent; import eu.musesproject.server.eventprocessor.impl.EventProcessorImpl; import eu.musesproject.server.risktrust.AccessRequest; import eu.musesproject.server.risktrust.Asset; import eu.musesproject.server.risktrust.Clue; import eu.musesproject.server.risktrust.Context; import eu.musesproject.server.risktrust.Decision; import eu.musesproject.server.risktrust.Device; import eu.musesproject.server.risktrust.DeviceSecurityState; import eu.musesproject.server.risktrust.DeviceTrustValue; import eu.musesproject.server.risktrust.Outcome; import eu.musesproject.server.risktrust.PolicyCompliance; import eu.musesproject.server.risktrust.Probability; import eu.musesproject.server.risktrust.RiskTreatment; import eu.musesproject.server.risktrust.Rt2ae; import eu.musesproject.server.risktrust.SecurityIncident; import eu.musesproject.server.risktrust.Threat; import eu.musesproject.server.risktrust.User; import eu.musesproject.server.risktrust.UserTrustValue; import eu.musesproject.server.scheduler.ModuleType; public class Rt2aeServerImpl implements Rt2ae { private final int RISK_TREATMENT_SIZE = 20; private Logger logger = Logger.getLogger(Rt2aeServerImpl.class.getName()); private DBManager dbManager = new DBManager(ModuleType.RT2AE); private RiskPolicy riskPolicy; String privateloungewifi = "Please go to the private lounge secure Wi-Fi"; String wifisniffing = "Wi-Fi sniffing"; String malwarerisktreatment = "Your device seems to have a Malware,please scan you device with an Antivirus or use another device"; /** * DecideBasedOnRiskPolicy is a function whose aim is to compute a Decision based on RiskPolicy. * @param accessRequest the access request * @param context the context */ @SuppressWarnings({"static-access" }) @Override public Decision decideBasedOnRiskPolicy(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub RiskPolicy rPolicy = new RiskPolicy(); Decision decision = Decision.STRONG_DENY_ACCESS; if(policyCompliance.getResult().equals(policyCompliance.DENY)){ decision.setInformation(policyCompliance.getReason()); return decision; } else{ return decideBasedOnRiskPolicy_version_6(accessRequest, rPolicy); } } /** * * This function is the version 6 of the decideBasedOnRiskPolicy. This * version computes the Decision based on the AccessRequest computing the * threats and their probabilities as well as accepting opportunities as * well if needed. It stores certain elements in the DB if needed. It also * compares against a risk policy. * * @param accessRequest * the access request * @return Decision * */ public Decision decideBasedOnRiskPolicy_version_6( AccessRequest accessRequest, RiskPolicy rPolicy) { // function variables and assignments double costOpportunity = 0.0; double combinedProbabilityThreats = 1.0; double combinedProbabilityOpportunities = 1.0; double singleThreatProbabibility = 0.0; double singleOpportunityProbability = 0.0; int opcount = 0; int threatcount = 0; Decision decision = Decision.STRONG_DENY_ACCESS; riskPolicy = rPolicy; EventProcessorImpl eventProcessorImpl = new EventProcessorImpl(); List<Asset> requestedAssets = new ArrayList<Asset>( Arrays.asList(accessRequest.getRequestedCorporateAsset())); List<Clue> clues = new ArrayList<Clue>(); // infer clues from the access request for (Asset asset : requestedAssets) { clues = eventProcessorImpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest .getDevice().getDevicetrustvalue()); Clue userName = new Clue(); userName.setName(accessRequest.getUser().toString()); // TODO // temporary // solution, // users // must have // nickname // or unique // identifier!! clues.add(userName); Clue assetName = new Clue(); assetName.setName(asset.getTitle()); clues.add(assetName); for (Clue clue : clues) { logger.info("The clue associated with Asset " + asset.getTitle() + " is " + clue.getName() + "\n"); } } List<eu.musesproject.server.entity.Threat> currentThreats = new ArrayList<eu.musesproject.server.entity.Threat>(); String threatName = ""; // combine clues with the asset and the user to generate a single threat for (Clue clue : clues) { threatName = threatName + clue.getName(); } eu.musesproject.server.entity.Threat threat = new eu.musesproject.server.entity.Threat(); threat.setDescription("Threat" + threatName); threat.setProbability(0.5); eu.musesproject.server.entity.Outcome o = new eu.musesproject.server.entity.Outcome(); o.setDescription("Compromised Asset"); o.setCostbenefit(-requestedAssets.iterator().next().getValue()); threat.setOutcomes(new ArrayList<eu.musesproject.server.entity.Outcome>( Arrays.asList(o))); // check if the threat already exists in the database dbManager.open(); boolean exists = false; List<eu.musesproject.server.entity.Threat> dbThreats = dbManager .getThreats(); eu.musesproject.server.entity.Threat existingThreat = new eu.musesproject.server.entity.Threat(); for (eu.musesproject.server.entity.Threat threat2 : dbThreats) { if (threat2.getDescription().equalsIgnoreCase( threat.getDescription())) { exists = true; existingThreat = threat2; } } // if doesn't exist, insert a new one if (!exists) { int oC = threat.getOccurences() + 1; threat.setOccurences(oC); currentThreats.add(threat); dbManager.setThreats(currentThreats); logger.info("The newly created Threat from the Clues is: " + threat.getDescription() + " with probability " + threat.getProbability() + " for the following outcome: \"" + threat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + threat.getOutcomes().iterator().next().getCostbenefit() + "\n"); // if already exists, update occurrences and update it in the // database } else { int oC = existingThreat.getOccurences() + 1; existingThreat.setOccurences(oC); currentThreats.add(existingThreat); logger.info("Occurences: " + existingThreat.getOccurences() + " - Bad Count: " + existingThreat.getBadOutcomeCount()); dbManager.setThreats(currentThreats); logger.info("The inferred Threat from the Clues is: " + existingThreat.getDescription() + " with probability " + existingThreat.getProbability() + " for the following outcome: \"" + existingThreat.getOutcomes().iterator().next() .getDescription() + "\" with the following potential cost (in kEUR): " + existingThreat.getOutcomes().iterator().next() .getCostbenefit() + "\n"); } dbManager.close(); // infer some probabilities from the threats and opportunities (if // present) for (eu.musesproject.server.entity.Threat t : currentThreats) { costOpportunity += t.getOutcomes().iterator().next() .getCostbenefit(); if (t.getOutcomes().iterator().next().getCostbenefit() < 0) { combinedProbabilityThreats = combinedProbabilityThreats * t.getProbability(); singleThreatProbabibility = singleThreatProbabibility + t.getProbability(); threatcount++; } else { combinedProbabilityOpportunities = combinedProbabilityOpportunities * t.getProbability(); singleOpportunityProbability = singleOpportunityProbability + t.getProbability(); opcount++; } } if (threatcount > 1) singleThreatProbabibility = singleThreatProbabibility - combinedProbabilityThreats; if (opcount > 1) singleOpportunityProbability = singleOpportunityProbability - combinedProbabilityOpportunities; // log some useful info logger.info("Decission data is: "); logger.info("- Risk Policy threshold: " + riskPolicy.getRiskvalue()); logger.info("- Cost Oportunity: " + costOpportunity); logger.info("- Combined Probability of the all possible Threats happening together: " + combinedProbabilityThreats); logger.info("- Combined Probability of the all the possible Opportunities happening together: " + combinedProbabilityOpportunities); logger.info("- Combined Probability of only one of the possible Threats happening: " + singleThreatProbabibility); logger.info("- Combined Probability of only one of the possible Opportunities happening: " + singleOpportunityProbability); logger.info("Making a decision..."); logger.info("."); logger.info(".."); logger.info("..."); // compute the decision based on the risk policy, the threat // probabilities, the user trust level and the cost benefit if (clues.get(0).getName().equalsIgnoreCase("Attempt to save a file in a monitored folder")) { decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Confidential data should not be stored on mobile devices unless it is absolutely necessary"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision.setRiskCommunication(riskCommunication); return decision; } if (clues.get(0).getName().contains("VIRUS")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); return decision; } if (clues.get(0).getName().contains("UnsecureWifi") && (accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("CONFIDENTIAL")||accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("STRICTLYCONFIDENTIAL"))){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("You are connected to an unsecure network, please connect to a secure network"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS: You are connected to an unsecure network, please connect to a secure network"); return decision; } /*if (riskPolicy.getRiskvalue() == 0.0) { decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } if (riskPolicy.getRiskvalue() == 1.0) { decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }*/ if ((combinedProbabilityThreats + ((Double) 1.0 - accessRequest .getUser().getUsertrustvalue().getValue())) / 2 <= riskPolicy .getRiskvalue()) { decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } else { if (costOpportunity > 0){ decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; logger.info("Decision: MAYBE_ACCESS_WITH_RISKTREATMENTS"); return decision; } else{ decision = Decision.STRONG_DENY_ACCESS; decision.setInformation(" There is too much risk in your situation to allow you to get access to the Asset"); logger.info("Decision: STRONG_DENY_ACCESS_WITH_RISKTREATMENTS"); return Decision.STRONG_DENY_ACCESS; } } } /** * This function is the version 1 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the AccessRequest * * @param accessRequest * @param context * @return */ @SuppressWarnings("static-access") public Decision decideBasedOnRiskPolicy_version_1(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; if (accessRequest.getRequestedCorporateAsset().getValue() <= 1000000 ) { Random r = new Random(); int valeur = 0 + r.nextInt(100 - 0); accessRequest.getUser().getUsertrustvalue().setValue(valeur); accessRequest.getDevice().getDevicetrustvalue().setValue(valeur); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; return decision; }else{ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } } else { decision = Decision.STRONG_DENY_ACCESS; return decision; } } /** * This function is the version 2 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats * * @param accessRequest * @param context * @return */ @SuppressWarnings("static-access") public Decision decideBasedOnRiskPolicy_version_2(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment1 = new RiskTreatment(malwarerisktreatment); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 3 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats and the Outcome * * @param accessRequest * @param context * @return */ @SuppressWarnings({ "unused", "static-access" }) public Decision decideBasedOnRiskPolicy_version_3(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Clue> clues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("TThere is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 4 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats and the Outcome and the trust value * * @param accessRequest * @param context * @return */ @SuppressWarnings({ "unused", "static-access" }) public Decision decideBasedOnRiskPolicy_version_4(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; Random r = new Random(); int valeur = 0 + r.nextInt(100 - 0); accessRequest.getUser().getUsertrustvalue().setValue(valeur); accessRequest.getDevice().getDevicetrustvalue().setValue(valeur); EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Clue> clues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 5 of the decideBasedOnRiskPolicy. This version computes the Decision based on the value of the Asset,the Context and the list of Threats and the Outcome and the trust value * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_version_5(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("public")){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("internal")){ if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionInternalAsset( accessRequest, context); } } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("confidential")){ if (!threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionConfidentialAsset(accessRequest, context); } } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("strictlyconfidential")){ if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionStrictlyConfidentialAsset( accessRequest, context); } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionInternalAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<=0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ logger.info("Decision: STRONG_DENY_ACCESS"); decision = Decision.STRONG_DENY_ACCESS; return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is less that 50% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; logger.info("Decision: MAYBE_ACCESS"); decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is more than 50% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<=0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 50% of chances that the asset that you wan to access will lose around 33% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()<0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/5); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 50% of chances that the asset that you wan to access will lose 20% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()>0){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionConfidentialAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Clue> clues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues Outcome requestPotentialOutcomes = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probabilitys = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcomes, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you want to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.7 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.7){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()<0.2){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()<0.3 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/5); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 20% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.7 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.7){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 20% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()<0.3){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()<0.3){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionStrictlyConfidentialAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Clue> clues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<0.1){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<0.1){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.1){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.1 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.9 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.9){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()<0.1){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()<0.1){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } /** * This function is the version of the decideBasedOnRiskPolicy for the demo Demo_Hambourg. * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_version_Demo_Hambourg(AccessRequest accessRequest, ConnectivityEvent connEvent) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; if (!connEvent.getWifiEncryption().equals("WPA2")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("Action not allowed. Please, change WIFI encryption to WPA2"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RiskTreatment: Action not allowed. Please, change WIFI encryption to WPA2"); return decision; }else{ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } } /** * This function is the version of the decideBasedOnRiskPolicy for the demo Demo_Hambourg. * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_testing_version(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); if(!policyCompliance.equals(policyCompliance.DENY)){ List<Clue> listclues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if (accessRequest.getRequestedCorporateAsset().getConfidential_level()=="PUBLIC"){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); logger.info("The confidential level of the asset is PUBLIC"); return decision; } for (int i = 0; i < listclues.size(); i++) { if (listclues.get(i).getName().equalsIgnoreCase("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setCondition("<noAttachments>1</noAttachments>");//TODO Manage this programmatically logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } /** * WarnDeviceSecurityStateChange is a function whose aim is to update the device trust value based on the new DeviceSecurityState. * @param deviceSecurityState the device security state */ @Override public void warnDeviceSecurityStateChange(DeviceSecurityState deviceSecurityState) { // TODO Auto-generated method stub dbManager.open(); eu.musesproject.server.entity.Device device = dbManager.findDeviceById(deviceSecurityState.getDevice_id()).get(0); int countadditionalprotection = device.getAdditionalProtections().size(); int countclues = deviceSecurityState.getClues().size(); deviceSecurityState.getDevice_id(); List<Clue> listclues = deviceSecurityState.getClues(); if(listclues.size()<=5){ device.setTrustValue(countadditionalprotection/(countadditionalprotection+countclues+1)); }else{ device.setTrustValue(countadditionalprotection/(countadditionalprotection+countclues)); } try { dbManager.merge(device); } catch (Exception e) { // TODO: handle exception } dbManager.close(); } /** * WarnUserSeemsInvolvedInSecurityIncident is a function whose aim is to check that if the user seems involved in security incident. * @param user the user * @param probability the probability * @param securityIncident the security incident */ @Override public void warnUserSeemsInvolvedInSecurityIncident(User user,Probability probability, SecurityIncident securityIncident) { // TODO Auto-generated method stub Random r = new Random(); double assetvalue = 0 + r.nextInt(1000000); /** * asset.getvalue():securityIncident.getCostBenefit() */ if(securityIncident.getCostBenefit() == 0){ /** * the security incident has not cost */ System.out.println(" securityIncident cost is 0"); }else { /** * security incident has a cost */ double pourcentage = securityIncident.getCostBenefit()/assetvalue; UserTrustValue u = new UserTrustValue(); u.setValue(user.getUsertrustvalue().getValue()-user.getUsertrustvalue().getValue()*pourcentage); user.setUsertrustvalue(u); } } public static void main (String [] arg){ Rt2aeServerImpl rt2ae = new Rt2aeServerImpl(); rt2ae = new Rt2aeServerImpl(); AccessRequest accessRequest = new AccessRequest(); accessRequest.setId(1); User user = new User(); UserTrustValue usertrustvalue = new UserTrustValue(); usertrustvalue.setValue(0); user.setUsertrustvalue(usertrustvalue); accessRequest.setUser(user); Device device = new Device(); DeviceTrustValue devicetrustvalue = new DeviceTrustValue(); devicetrustvalue.setValue(0); device.setDevicetrustvalue(devicetrustvalue); accessRequest.setDevice(device); Asset requestedCorporateAsset = new Asset(); requestedCorporateAsset.setValue(1000000); requestedCorporateAsset.setConfidential_level("confidential"); accessRequest.setRequestedCorporateAsset(requestedCorporateAsset); RiskPolicy rPolicy = new RiskPolicy(); Decision decision2 = rt2ae.decideBasedOnRiskPolicy_version_6(accessRequest, rPolicy); System.out.println("Decision: "+decision2.toString()); } }
package io.github.sporklibrary.utils; import android.app.Activity; import android.app.Application; import android.app.Fragment; import android.content.ContentProvider; import android.content.Context; import android.view.View; import io.github.sporklibrary.exceptions.NotInstantiatableException; import io.github.sporklibrary.utils.support.SupportFragments; import io.github.sporklibrary.utils.support.SupportLibraries; public final class ContextResolver { private ContextResolver() { throw new NotInstantiatableException(getClass()); } public static Context getContext(Object object) { Class<?> object_class = object.getClass(); if (View.class.isAssignableFrom(object_class)) { return ((View)object).getContext(); } else if (Fragment.class.isAssignableFrom(object_class)) { return ((Fragment)object).getActivity(); } else if (Activity.class.isAssignableFrom(object_class)) { return (Activity)object; } else if (Application.class.isAssignableFrom(object_class)) { return (Application)object; } else if (ContentProvider.class.isAssignableFrom(object_class)) { return ((ContentProvider)object).getContext(); } else if (SupportFragments.isFragmentClass(object_class)) { return ((android.support.v4.app.Fragment)object).getActivity(); } else if (SupportLibraries.hasRecyclerViewV7() && android.support.v7.widget.RecyclerView.ViewHolder.class.isAssignableFrom(object_class)) { return ((android.support.v7.widget.RecyclerView.ViewHolder)object).itemView.getContext(); } else { return null; } } }
package array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * public class BubleSort it sort array the method of buble. * @author greensow25. * @since 30.11.16. * @version 1. */ public class BubleSortTest { /** * method. */ @Test public void whenEnterArraythenOutSortArray() { BubleSort sort = new BubleSort(); final int ar = 7; final int arr = 30; int[]testarray = new int[ar]; for (int i = 0; i <= testarray.length - 1; i++) { testarray[i] = (int) (Math.random() * arr); } int[]expectedarray = sort.sort(testarray); assertThat(expectedarray, is(testarray)); } }
package ru.agolovin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Random; public class Chat { /** * Stop. */ private final String STOP = "закончить"; /** * Pause. */ private final String PAUSE = "стоп"; /** * Continue. */ private final String REPEAT = "продолжить"; /** * Input. */ private Input input; /** * Array list String. */ private ArrayList<String> arrayComputerWords; /** * Computer words file. */ private File computerWords; /** * log. */ private File log; /** * Constructor. * @param input Input */ Chat(Input input) { this.input = input; computerWords = new File("word.txt"); log = new File("log.txt"); arrayComputerWords = new ArrayList<>(); } /** * Fill Array from File. * @param file File */ private void fillArrayFromFile(File file) { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); String line; while ((line = raf.readLine()) != null) { String convert = new String(line.getBytes("windows-1251"), "UTF-8"); arrayComputerWords.add(convert); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { raf.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * Get Random number from range. * @param rows int * @return random number int */ int getRandomNumberFromRange(int rows) { int result; Random random = new Random(); result = random.nextInt(rows); return result; } /** * Chat. * @throws Exception exception */ public void chat() throws Exception { FileWriter fileWriter = null; String lineSeparator = System.getProperty("line.separator"); try { boolean stopFlag = false; fillArrayFromFile(computerWords); int maxNumberRow = arrayComputerWords.size(); String answer; if (log.exists() && log.isFile()) { if (!log.delete()) { throw new Exception("Cant reset log"); } if (!log.createNewFile()) { throw new Exception("Cant create log"); } } else { if (!log.createNewFile()) { throw new Exception("Cant create log"); } } fileWriter = new FileWriter(log); do { boolean flag = true; answer = input.ask("Пользователь:"); System.out.println(String.format("Пользователь: %s", answer)); fileWriter.write(answer); fileWriter.write(lineSeparator); if (PAUSE.equals(answer.toLowerCase())) { stopFlag = true; } else if (REPEAT.equals(answer.toLowerCase())) { stopFlag = false; } else if (STOP.equals(answer.toLowerCase())) { flag = false; } if (!stopFlag && flag) { String line = arrayComputerWords.get(getRandomNumberFromRange(maxNumberRow)); System.out.println(String.format("Компьютер: %s", line)); fileWriter.write(line); fileWriter.write(lineSeparator); } } while (!STOP.equals(answer.toLowerCase())); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } }
package learn_to_code.java_api.stream; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.IntConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; public class UsingStreamApi { public static void main(String[] args) { int[] array = new int[20]; for (int i = 0; i < array.length; i++) { array[i] = i / 2; } /* You can get stream both from collections and from arrays. * When using arrays, you can even get primitive type streams by using classes such as * IntStream, DoubleStream or LongStream * * Remember, that you can open stream AND use it immediately, because opening a stream is not finishing operation */ IntStream arrayStream = Arrays.stream(array); /* Here we print all elements from array, using .forEach. forEach takes a consumer which means * it uses an element but does not return any value */ System.out.print("initial array: "); IntConsumer printInLine = element -> System.out.printf("%3d ", element); arrayStream.forEach(printInLine); System.out.println(); /* Remember that .forEach is finishing operation which mean you can not use the same stream again for anything else * and you have to recreate it. * * Also take note that filter IS NOT finishing operation, that's why we can use forEach() after using filter() * * The filter takes each element in given stream and either add it to new stream or now. If filter return true for element * it will be added to output stream*/ arrayStream = Arrays.stream(array); System.out.print("even elements: "); arrayStream.filter((element) -> (element % 2 == 0)).forEach(printInLine); System.out.println(); /* Reduce() turn your stream into a single value. It first takes 2 elements of streams, apply a BiFunction with method "CLASS apply(CLASS element1, CLASS element2)" which return a values and then use the result as the first element for next iteration. E.g. when summing values 1,2,3,4 reduce will go as following: * iteration 1. 0 + 1 = 1 * iteration 2. 1 + 2 = 3 * iteration 3. 3 + 3 = 6 * iteration 4. 6 + 4 = 10. * * Take note for the first argument and first iteration. The first value is called identity value and it * should satisfy equation * apply( x, IDENTITY_VALUE) = x * * e.g. for summing the identity_value is 0, because x + 0 = x. * For multiplying it would be 1, because x * 1 = x, etc * */ arrayStream = Arrays.stream(array); System.out.println("sum of elements: " + arrayStream.reduce(0, (a, b) -> (a + b))); /* Maps each values from input stream to output stream using provided function. Is NOT finishing operation */ arrayStream = Arrays.stream(array); System.out.print("doubled elements: "); arrayStream.map((element) -> element * 2).forEach(printInLine); System.out.println(); String[] names = {"Ivan", "Vasili", "John", "Bob", "Katya"}; String resultParallel = Arrays.stream(names).parallel().collect(StringBuilder::new, (elementsSoFar, newElement) -> elementsSoFar.append(" ").append(newElement), (firstParallelTask, secondParallelTask) -> firstParallelTask.append(",").append(secondParallelTask)) .deleteCharAt(0).toString(); String resultSequential = Arrays.stream(names).sequential().collect(StringBuilder::new, (elementsSoFar, newElement) -> elementsSoFar.append(", ").append(newElement), (firstParallelTask, secondParallelTask) -> System.out.println("I am actually getting called!")) .delete(0, 2).toString(); System.out.printf("%20s \"%s\"\n", "result parallel:", resultParallel); System.out.printf("%20s \"%s\"\n", "result sequential:", resultSequential); /* Also note, that collect method can be used to get COLLECTIONS from your streams using * predefined static methods in Collectors class such as toSet() toList(), toMap(), toConcurrentMap()*/ Set<String> namesAsSet = Arrays.stream(names).collect(Collectors.toSet()); System.out.printf("%20s", "Elements in set 1: \""); namesAsSet.stream().forEach((e) -> System.out.print(e + " ")); System.out.print("\"\n"); /* Instead of calling toSet you can actually do something like this:*/ namesAsSet = Arrays.stream(names).collect(HashSet::new, HashSet::add, HashSet::addAll); System.out.printf("%20s", "Elements in set 2: \""); namesAsSet.stream().forEach((e) -> System.out.print(e + " ")); System.out.print("\"\n"); /* Or like this: */ namesAsSet = Arrays.stream(names).collect(() -> new HashSet(), (set, element) -> set.add(element), (set1, set2) -> set1.addAll(set2)); System.out.printf("%20s", "Elements in set 3: \""); namesAsSet.stream().forEach((e) -> System.out.print(e + " ")); System.out.print("\"\n"); } }
package cn.jingzhuan.lib.chart; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.os.Build; import android.support.annotation.FloatRange; import android.support.annotation.IntRange; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.support.v4.widget.EdgeEffectCompat; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.widget.OverScroller; import cn.jingzhuan.lib.chart.utils.ForceAlign; import cn.jingzhuan.lib.chart.utils.ForceAlign.XForce; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import cn.jingzhuan.lib.chart.R; import cn.jingzhuan.lib.chart.component.Axis; import cn.jingzhuan.lib.chart.component.AxisX; import cn.jingzhuan.lib.chart.component.AxisY; import cn.jingzhuan.lib.chart.component.Highlight; import cn.jingzhuan.lib.chart.event.OnViewportChangeListener; public abstract class Chart extends View { protected AxisY mAxisLeft = new AxisY(AxisY.LEFT_INSIDE); protected AxisY mAxisRight = new AxisY(AxisY.RIGHT_INSIDE); protected AxisX mAxisTop = new AxisX(AxisX.TOP); protected AxisX mAxisBottom = new AxisX(AxisX.BOTTOM); // State objects and values related to gesture tracking. private ScaleGestureDetector mScaleGestureDetector; private GestureDetectorCompat mGestureDetector; private OverScroller mScroller; private Zoomer mZoomer; private PointF mZoomFocalPoint = new PointF(); private RectF mScrollerStartViewport = new RectF(); // Used only for zooms and flings. private boolean mScaleXEnable = true; private boolean mDraggingToMoveEnable = true; private boolean mDoubleTapToZoom = false; protected List<OnTouchPointChangeListener> mTouchPointChangeListeners; private List<OnViewportChangeListener> mOnViewportChangeListeners; protected OnViewportChangeListener mInternalViewportChangeListener; /** * The current viewport. This rectangle represents the currently visible lib domain * and range. The currently visible lib X values are from this rectangle's left to its right. * The currently visible lib Y values are from this rectangle's top to its bottom. * <p> * Note that this rectangle's top is actually the smaller Y value, and its bottom is the larger * Y value. Since the lib is drawn onscreen in such a way that lib Y values increase * towards the top of the screen (decreasing pixel Y positions), this rectangle's "top" is drawn * above this rectangle's "bottom" value. * * @see #mContentRect */ private Viewport mCurrentViewport = new Viewport(); /** * The current destination rectangle (in pixel coordinates) into which the lib data should * be drawn. Chart labels are drawn outside this area. * * @see #mCurrentViewport */ private Rect mContentRect = new Rect(); /** * The scaling factor for a single zoom 'step'. * * @see #zoomIn() * @see #zoomOut() */ private static final float ZOOM_AMOUNT = 0.25f; private Point mSurfaceSizeBuffer = new Point(); // Edge effect / overscroll tracking objects. private EdgeEffectCompat mEdgeEffectTop; private EdgeEffectCompat mEdgeEffectBottom; private EdgeEffectCompat mEdgeEffectLeft; private EdgeEffectCompat mEdgeEffectRight; private boolean mEdgeEffectTopActive; private boolean mEdgeEffectBottomActive; private boolean mEdgeEffectLeftActive; private boolean mEdgeEffectRightActive; public Chart(Context context) { this(context, null, 0); } public Chart(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public Chart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public Chart(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.Chart, defStyleAttr, defStyleAttr); mTouchPointChangeListeners = new CopyOnWriteArrayList<>(); mOnViewportChangeListeners = new CopyOnWriteArrayList<>(); mAxisTop.setGridLineEnable(false); mAxisTop.setLabelEnable(false); try { List<Axis> axisList = new ArrayList<>(4); axisList.add(mAxisLeft); axisList.add(mAxisRight); axisList.add(mAxisTop); axisList.add(mAxisBottom); float labelTextSize = a.getDimension(R.styleable.Chart_labelTextSize, 28); float labelSeparation = a.getDimensionPixelSize(R.styleable.Chart_labelSeparation, 10); float gridThickness = a.getDimension(R.styleable.Chart_gridThickness, 2); float axisThickness = a.getDimension(R.styleable.Chart_axisThickness, 2); int gridColor = a.getColor(R.styleable.Chart_gridColor, Color.GRAY); int axisColor = a.getColor(R.styleable.Chart_axisColor, Color.GRAY); int labelTextColor = a.getColor(R.styleable.Chart_labelTextColor, Color.GRAY); for (Axis axis : axisList) { axis.setLabelTextSize(labelTextSize); axis.setLabelTextColor(labelTextColor); axis.setLabelSeparation(labelSeparation); axis.setGridColor(gridColor); axis.setGridThickness(gridThickness); axis.setAxisColor(axisColor); axis.setAxisThickness(axisThickness); } } finally { a.recycle(); } initChart(); setupInteractions(context); setupEdgeEffect(context); } public abstract void initChart(); public abstract void highlightValue(Highlight highlight); public abstract void cleanHighlight(); @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mContentRect.set( getPaddingLeft() + mAxisLeft.getMaxLabelWidth() + (mAxisLeft.isInside() ? 0 : mAxisLeft.getLabelSeparation()), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom() - mAxisBottom.getLabelHeight() - mAxisBottom.getLabelSeparation()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int minChartSize = getResources().getDimensionPixelSize(R.dimen.jz_chart_min_size); setMeasuredDimension( Math.max(getSuggestedMinimumWidth(), resolveSize(minChartSize + getPaddingLeft() + (mAxisLeft.isInside() ? 0 : mAxisLeft.getMaxLabelWidth()) + (mAxisLeft.isInside() ? 0 : mAxisLeft.getLabelSeparation()) + getPaddingRight(), widthMeasureSpec)), Math.max(getSuggestedMinimumHeight(), resolveSize(minChartSize + getPaddingTop() + (mAxisBottom.isInside() ? 0 : mAxisBottom.getLabelHeight()) + (mAxisBottom.isInside() ? 0 : mAxisBottom.getLabelSeparation()) + getPaddingBottom(), heightMeasureSpec))); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawAxis(canvas); // Clips the next few drawing operations to the content area int clipRestoreCount = canvas.save(); canvas.clipRect(mContentRect); render(canvas); drawEdgeEffectsUnclipped(canvas); // Removes clipping rectangle canvas.restoreToCount(clipRestoreCount); drawLabels(canvas); } protected abstract void drawAxis(Canvas canvas); protected abstract void drawLabels(Canvas canvas); protected abstract void render(Canvas canvas); public Viewport getCurrentViewport() { return mCurrentViewport; } public Rect getContentRect() { return mContentRect; } private void setupInteractions(Context context) { mScaleGestureDetector = new ScaleGestureDetector(context, mScaleGestureListener); mGestureDetector = new GestureDetectorCompat(context, mGestureListener); mScroller = new OverScroller(context); mZoomer = new Zoomer(context); } /** * Finds the lib point (i.e. within the lib's domain and range) represented by the * given pixel coordinates, if that pixel is within the lib region described by * {@link #mContentRect}. If the point is found, the "dest" argument is set to the point and * this function returns true. Otherwise, this function returns false and "dest" is unchanged. */ private boolean hitTest(float x, float y, PointF dest) { if (!mContentRect.contains((int) x, (int) y)) { return false; } dest.set(mCurrentViewport.left + mCurrentViewport.width() * (x - mContentRect.left) / mContentRect.width(), mCurrentViewport.top + mCurrentViewport.height() * (y - mContentRect.bottom) / -mContentRect.height()); return true; } /** * The scale listener, used for handling multi-finger scale gestures. */ private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() { /** * This is the active focal point in terms of the viewport. Could be a local * variable but kept here to minimize per-frame allocations. */ private PointF viewportFocus = new PointF(); private float lastSpanX; // private float lastSpanY; @Override public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { lastSpanX = ScaleGestureDetectorCompat.getCurrentSpanX(scaleGestureDetector); // lastSpanY = ScaleGestureDetectorCompat.getCurrentSpanY(scaleGestureDetector); return true; } @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { if (!mScaleXEnable) return false; float spanX = ScaleGestureDetectorCompat.getCurrentSpanX(scaleGestureDetector); float spanY = ScaleGestureDetectorCompat.getCurrentSpanY(scaleGestureDetector); float newWidth = lastSpanX / spanX * mCurrentViewport.width(); // float newHeight = lastSpanY / spanY * mCurrentViewport.height(); if (newWidth < mCurrentViewport.width() && mCurrentViewport.width() < 0.1) { return true; } float focusX = scaleGestureDetector.getFocusX(); float focusY = scaleGestureDetector.getFocusY(); hitTest(focusX, focusY, viewportFocus); mCurrentViewport.left = viewportFocus.x - newWidth * (focusX - mContentRect.left) / mContentRect.width(); // mCurrentViewport.set( // viewportFocus.x // - newWidth * (focusX - mContentRect.left) // / mContentRect.width(), // viewportFocus.y // - newHeight * (mContentRect.bottom - focusY) // / mContentRect.height(), mCurrentViewport.right = mCurrentViewport.left + newWidth; // mCurrentViewport.bottom = mCurrentViewport.top + newHeight; mCurrentViewport.constrainViewport(); //ViewCompat.postInvalidateOnAnimation(Chart.this); if (mScaleXEnable) notifyViewportChange(); lastSpanX = spanX; // lastSpanY = spanY; return true; } }; protected abstract void onTouchPoint(float x, float y); /** * The gesture listener, used for handling simple gestures such as double touches, scrolls, * and flings. */ private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { releaseEdgeEffects(); mScrollerStartViewport.set(mCurrentViewport); mScroller.forceFinished(true); ViewCompat.postInvalidateOnAnimation(Chart.this); return true; } @Override public void onShowPress(MotionEvent e) { super.onShowPress(e); onTouchPoint(e.getX(), e.getY()); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { cleanHighlight(); return super.onSingleTapConfirmed(e); } @Override public boolean onDoubleTap(MotionEvent e) { if (mDoubleTapToZoom) { mZoomer.forceFinished(true); if (hitTest(e.getX(), e.getY(), mZoomFocalPoint)) { mZoomer.startZoom(ZOOM_AMOUNT); } ViewCompat.postInvalidateOnAnimation(Chart.this); } return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!isDraggingToMoveEnable()) { onTouchPoint(e2.getX(), e2.getY()); return super.onScroll(e1, e2, distanceX, distanceY); } // Scrolling uses math based on the viewport (as opposed to math using pixels). /** * Pixel offset is the offset in screen pixels, while viewport offset is the * offset within the current viewport. For additional information on surface sizes * and pixel offsets, see the docs for {@link computeScrollSurfaceSize()}. For * additional information about the viewport, see the comments for * {@link mCurrentViewport}. */ float viewportOffsetX = distanceX * mCurrentViewport.width() / mContentRect.width(); float viewportOffsetY = -distanceY * mCurrentViewport.height() / mContentRect.height(); computeScrollSurfaceSize(mSurfaceSizeBuffer); int scrolledX = (int) (mSurfaceSizeBuffer.x * (mCurrentViewport.left + viewportOffsetX - Viewport.AXIS_X_MIN) / (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN)); int scrolledY = (int) (mSurfaceSizeBuffer.y * (Viewport.AXIS_Y_MAX - mCurrentViewport.bottom - viewportOffsetY) / (Viewport.AXIS_Y_MAX - Viewport.AXIS_Y_MIN)); boolean canScrollX = mCurrentViewport.left > Viewport.AXIS_X_MIN || mCurrentViewport.right < Viewport.AXIS_X_MAX; boolean canScrollY = mCurrentViewport.top > Viewport.AXIS_Y_MIN || mCurrentViewport.bottom < Viewport.AXIS_Y_MAX; setViewportBottomLeft( mCurrentViewport.left + viewportOffsetX, mCurrentViewport.bottom + viewportOffsetY); if (canScrollX && scrolledX < 0) { mEdgeEffectLeft.onPull(scrolledX / (float) mContentRect.width()); mEdgeEffectLeftActive = true; } if (canScrollY && scrolledY < 0) { mEdgeEffectTop.onPull(scrolledY / (float) mContentRect.height()); mEdgeEffectTopActive = true; } if (canScrollX && scrolledX > mSurfaceSizeBuffer.x - mContentRect.width()) { mEdgeEffectRight.onPull((scrolledX - mSurfaceSizeBuffer.x + mContentRect.width()) / (float) mContentRect.width()); mEdgeEffectRightActive = true; } if (canScrollY && scrolledY > mSurfaceSizeBuffer.y - mContentRect.height()) { mEdgeEffectBottom.onPull((scrolledY - mSurfaceSizeBuffer.y + mContentRect.height()) / (float) mContentRect.height()); mEdgeEffectBottomActive = true; } onTouchPoint(e2.getX(), e2.getY()); //notifyViewportChange(); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (!isDraggingToMoveEnable()) return super.onFling(e1, e2, velocityX, velocityY); fling((int) -velocityX, (int) -velocityY); onTouchPoint(e2.getX(), e2.getY()); return true; } }; private void notifyViewportChange() { if (mInternalViewportChangeListener != null) { mInternalViewportChangeListener.onViewportChange(mCurrentViewport); } if (mOnViewportChangeListeners != null) { for (OnViewportChangeListener mOnViewportChangeListener : mOnViewportChangeListeners) { mOnViewportChangeListener.onViewportChange(mCurrentViewport); } } ViewCompat.postInvalidateOnAnimation(this); } private void fling(int velocityX, int velocityY) { releaseEdgeEffects(); // Flings use math in pixels (as opposed to math based on the viewport). computeScrollSurfaceSize(mSurfaceSizeBuffer); mScrollerStartViewport.set(mCurrentViewport); int startX = (int) (mSurfaceSizeBuffer.x * (mScrollerStartViewport.left - Viewport.AXIS_X_MIN) / ( Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN)); int startY = (int) (mSurfaceSizeBuffer.y * (Viewport.AXIS_Y_MAX - mScrollerStartViewport.bottom) / ( Viewport.AXIS_Y_MAX - Viewport.AXIS_Y_MIN)); mScroller.forceFinished(true); mScroller.fling( startX, startY, velocityX, velocityY, 0, mSurfaceSizeBuffer.x - mContentRect.width(), 0, mSurfaceSizeBuffer.y - mContentRect.height(), mContentRect.width() / 2, mContentRect.height() / 2); ViewCompat.postInvalidateOnAnimation(this); //notifyViewportChange(); } /** * Computes the current scrollable surface size, in pixels. For example, if the entire lib * area is visible, this is simply the current size of {@link #mContentRect}. If the lib * is zoomed in 200% in both directions, the returned size will be twice as large horizontally * and vertically. */ private void computeScrollSurfaceSize(Point out) { out.set((int) (mContentRect.width() * (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN) / mCurrentViewport.width()), (int) (mContentRect.height() * (Viewport.AXIS_Y_MAX - Viewport.AXIS_Y_MIN) / mCurrentViewport.height())); } /** * Smoothly zooms the lib in one step. */ public void zoomIn() { mScrollerStartViewport.set(mCurrentViewport); mZoomer.forceFinished(true); mZoomer.startZoom(ZOOM_AMOUNT); mZoomFocalPoint.set( (mCurrentViewport.right + mCurrentViewport.left) / 2, (mCurrentViewport.bottom + mCurrentViewport.top) / 2); ViewCompat.postInvalidateOnAnimation(this); } /** * Smoothly zooms the lib out one step. */ public void zoomOut() { mScrollerStartViewport.set(mCurrentViewport); mZoomer.forceFinished(true); mZoomer.startZoom(-ZOOM_AMOUNT); mZoomFocalPoint.set( (mCurrentViewport.right + mCurrentViewport.left) / 2, (mCurrentViewport.bottom + mCurrentViewport.top) / 2); notifyViewportChange(); } public void zoomOut(@XForce int forceAlignX) { mScrollerStartViewport.set(mCurrentViewport); mZoomer.forceFinished(true); mZoomer.startZoom(-ZOOM_AMOUNT); float forceX; switch (forceAlignX) { case ForceAlign.LEFT: forceX = mCurrentViewport.left; break; case ForceAlign.RIGHT: forceX = mCurrentViewport.right; break; case ForceAlign.CENTER: forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2; break; default: forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2; break; } mZoomFocalPoint.set(forceX, (mCurrentViewport.bottom + mCurrentViewport.top) / 2); ViewCompat.postInvalidateOnAnimation(this); } /** * Smoothly zooms the lib in one step. */ public void zoomIn(@XForce int forceAlignX) { mScrollerStartViewport.set(mCurrentViewport); mZoomer.forceFinished(true); mZoomer.startZoom(ZOOM_AMOUNT); float forceX; switch (forceAlignX) { case ForceAlign.LEFT: forceX = mCurrentViewport.left; break; case ForceAlign.RIGHT: forceX = mCurrentViewport.right; break; case ForceAlign.CENTER: forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2; break; default: forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2; break; } mZoomFocalPoint.set(forceX, (mCurrentViewport.bottom + mCurrentViewport.top) / 2); notifyViewportChange(); } @Override public void computeScroll() { super.computeScroll(); boolean needsInvalidate = false; if (mScroller.computeScrollOffset()) { // The scroller isn't finished, meaning a fling or programmatic pan operation is // currently active. computeScrollSurfaceSize(mSurfaceSizeBuffer); int currX = mScroller.getCurrX(); int currY = mScroller.getCurrY(); boolean canScrollX = (mCurrentViewport.left > Viewport.AXIS_X_MIN || mCurrentViewport.right < Viewport.AXIS_X_MAX); boolean canScrollY = (mCurrentViewport.top > Viewport.AXIS_Y_MIN || mCurrentViewport.bottom < Viewport.AXIS_Y_MAX); if (canScrollX && currX < 0 && mEdgeEffectLeft.isFinished() && !mEdgeEffectLeftActive) { mEdgeEffectLeft.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectLeftActive = true; needsInvalidate = true; } else if (canScrollX && currX > (mSurfaceSizeBuffer.x - mContentRect.width()) && mEdgeEffectRight.isFinished() && !mEdgeEffectRightActive) { mEdgeEffectRight.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectRightActive = true; needsInvalidate = true; } if (canScrollY && currY < 0 && mEdgeEffectTop.isFinished() && !mEdgeEffectTopActive) { mEdgeEffectTop.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectTopActive = true; needsInvalidate = true; } else if (canScrollY && currY > (mSurfaceSizeBuffer.y - mContentRect.height()) && mEdgeEffectBottom.isFinished() && !mEdgeEffectBottomActive) { mEdgeEffectBottom.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectBottomActive = true; needsInvalidate = true; } float currXRange = Viewport.AXIS_X_MIN + (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN) * currX / mSurfaceSizeBuffer.x; float currYRange = Viewport.AXIS_Y_MAX - (Viewport.AXIS_Y_MAX - Viewport.AXIS_Y_MIN) * currY / mSurfaceSizeBuffer.y; setViewportBottomLeft(currXRange, currYRange); } if (mZoomer.computeZoom()) { // Performs the zoom since a zoom is in progress (either programmatically or via // double-touch). float newWidth = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.width(); float newHeight = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.height(); float pointWithinViewportX = (mZoomFocalPoint.x - mScrollerStartViewport.left) / mScrollerStartViewport.width(); float pointWithinViewportY = (mZoomFocalPoint.y - mScrollerStartViewport.top) / mScrollerStartViewport.height(); mCurrentViewport.set( mZoomFocalPoint.x - newWidth * pointWithinViewportX, mZoomFocalPoint.y - newHeight * pointWithinViewportY, mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX), mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY)); mCurrentViewport.constrainViewport(); needsInvalidate = true; } if (needsInvalidate) { //ViewCompat.postInvalidateOnAnimation(this); notifyViewportChange(); } } /** * Sets the current viewport (defined by {@link #mCurrentViewport}) to the given * X and Y positions. Note that the Y value represents the topmost pixel position, and thus * the bottom of the {@link #mCurrentViewport} rectangle. For more details on why top and * bottom are flipped, see {@link #mCurrentViewport}. */ private void setViewportBottomLeft(float x, float y) { /** * Constrains within the scroll range. The scroll range is simply the viewport extremes * (AXIS_X_MAX, etc.) minus the viewport size. For example, if the extrema were 0 and 10, * and the viewport size was 2, the scroll range would be 0 to 8. */ float curWidth = mCurrentViewport.width(); float curHeight = mCurrentViewport.height(); x = Math.max(Viewport.AXIS_X_MIN, Math.min(x, Viewport.AXIS_X_MAX - curWidth)); y = Math.max(Viewport.AXIS_Y_MIN + curHeight, Math.min(y, Viewport.AXIS_Y_MAX)); mCurrentViewport.set(x, y - curHeight, x + curWidth, y); notifyViewportChange(); } /** * Sets the lib's current viewport. * * @see #getCurrentViewport() */ public void setCurrentViewport(RectF viewport) { mCurrentViewport = new Viewport(viewport); mCurrentViewport.constrainViewport(); notifyViewportChange(); } @Override public boolean onTouchEvent(MotionEvent event) { boolean retVal = event.getPointerCount() > 1 && mScaleGestureDetector.onTouchEvent(event); retVal = mGestureDetector.onTouchEvent(event) || retVal; return retVal || super.onTouchEvent(event); } protected void setupEdgeEffect(Context context) { // Sets up edge effects mEdgeEffectLeft = new EdgeEffectCompat(context); mEdgeEffectTop = new EdgeEffectCompat(context); mEdgeEffectRight = new EdgeEffectCompat(context); mEdgeEffectBottom = new EdgeEffectCompat(context); } /** * Draws the overscroll "glow" at the four edges of the lib region, if necessary. The edges * of the lib region are stored in {@link #mContentRect}. * * @see EdgeEffectCompat */ private void drawEdgeEffectsUnclipped(Canvas canvas) { // The methods below rotate and translate the canvas as needed before drawing the glow, // since EdgeEffectCompat always draws a top-glow at 0,0. boolean needsInvalidate = false; if (!mEdgeEffectTop.isFinished()) { final int restoreCount = canvas.save(); canvas.translate(mContentRect.left, mContentRect.top); mEdgeEffectTop.setSize(mContentRect.width(), mContentRect.height()); if (mEdgeEffectTop.draw(canvas)) { needsInvalidate = true; } canvas.restoreToCount(restoreCount); } if (!mEdgeEffectBottom.isFinished()) { final int restoreCount = canvas.save(); canvas.translate(2 * mContentRect.left - mContentRect.right, mContentRect.bottom); canvas.rotate(180, mContentRect.width(), 0); mEdgeEffectBottom.setSize(mContentRect.width(), mContentRect.height()); if (mEdgeEffectBottom.draw(canvas)) { needsInvalidate = true; } canvas.restoreToCount(restoreCount); } if (!mEdgeEffectLeft.isFinished()) { final int restoreCount = canvas.save(); canvas.translate(mContentRect.left, mContentRect.bottom); canvas.rotate(-90, 0, 0); mEdgeEffectLeft.setSize(mContentRect.height(), mContentRect.width()); if (mEdgeEffectLeft.draw(canvas)) { needsInvalidate = true; } canvas.restoreToCount(restoreCount); } if (!mEdgeEffectRight.isFinished()) { final int restoreCount = canvas.save(); canvas.translate(mContentRect.right, mContentRect.top); canvas.rotate(90, 0, 0); mEdgeEffectRight.setSize(mContentRect.height(), mContentRect.width()); if (mEdgeEffectRight.draw(canvas)) { needsInvalidate = true; } canvas.restoreToCount(restoreCount); } if (needsInvalidate) { //ViewCompat.postInvalidateOnAnimation(this); notifyViewportChange(); } } private void releaseEdgeEffects() { mEdgeEffectLeftActive = mEdgeEffectTopActive = mEdgeEffectRightActive = mEdgeEffectBottomActive = false; mEdgeEffectLeft.onRelease(); mEdgeEffectTop.onRelease(); mEdgeEffectRight.onRelease(); mEdgeEffectBottom.onRelease(); } public AxisY getAxisLeft() { return mAxisLeft; } public AxisY getAxisRight() { return mAxisRight; } public AxisX getAxisTop() { return mAxisTop; } public AxisX getAxisBottom() { return mAxisBottom; } public void addOnViewportChangeListener(OnViewportChangeListener onViewportChangeListener) { this.mOnViewportChangeListeners.add(onViewportChangeListener); } public boolean isScaleXEnable() { return mScaleXEnable; } public void setScaleXEnable(boolean scaleXEnable) { this.mScaleXEnable = scaleXEnable; } public void setDoubleTapToZoom(boolean doubleTapToZoom) { this.mDoubleTapToZoom = doubleTapToZoom; } public interface OnTouchPointChangeListener { void touch(float x, float y); } public void addOnTouchPointChangeListener(OnTouchPointChangeListener touchPointChangeListener) { this.mTouchPointChangeListeners.add(touchPointChangeListener); } public void removeOnTouchPointChangeListener(OnTouchPointChangeListener touchPointChangeListener) { this.mTouchPointChangeListeners.remove(touchPointChangeListener); } public void setDraggingToMoveEnable(boolean draggingToMoveEnable) { this.mDraggingToMoveEnable = draggingToMoveEnable; } public boolean isDraggingToMoveEnable() { return mDraggingToMoveEnable; } public void moveLeft() { moveLeft(0.1f); } public void moveRight() { moveRight(0.1f); } public void moveLeft(@FloatRange(from = 0f, to = 1.0f) float percent) { float moveDistance = mCurrentViewport.width() * percent; boolean canMoveLeft = (mCurrentViewport.left - moveDistance > Viewport.AXIS_X_MIN); if (canMoveLeft) { mCurrentViewport.left = mCurrentViewport.left - moveDistance; mCurrentViewport.right = mCurrentViewport.right - moveDistance; } else { mCurrentViewport.left = mCurrentViewport.left - moveDistance; } mCurrentViewport.constrainViewport(); notifyViewportChange(); } public void moveRight(@FloatRange(from = 0f, to = 1.0f) float percent) { float moveDistance = mCurrentViewport.width() * percent; boolean canMoveRight = (mCurrentViewport.right + moveDistance < Viewport.AXIS_X_MAX); if (canMoveRight) { mCurrentViewport.left = mCurrentViewport.left + moveDistance; mCurrentViewport.right = mCurrentViewport.right + moveDistance; } else { mCurrentViewport.right = mCurrentViewport.right + moveDistance; } mCurrentViewport.constrainViewport(); notifyViewportChange(); } public void setInternalViewportChangeListener( OnViewportChangeListener mInternalViewportChangeListener) { this.mInternalViewportChangeListener = mInternalViewportChangeListener; } }
package net.eldeen.dropwizard; import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.cloudformation.AmazonCloudFormation; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.ResourceSignalStatus; import com.amazonaws.services.cloudformation.model.SignalResourceRequest; import com.amazonaws.util.EC2MetadataUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.base.Throwables; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.util.component.LifeCycle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Signal the AutoScalingGroup via CloudFormation Signal when running on an AWS EC2 instance. */ public class CfSignalResourceBundle<T extends Configuration> implements ConfiguredBundle<T> { private static final Logger LOGGER = LoggerFactory.getLogger(CfSignalResourceBundle.class); private final Function<CfSignalResourceConfig, AmazonCloudFormation> cloudFormationSupplier; private final AtomicReference<AmazonCloudFormation> internalCloudFormation = new AtomicReference<>(null); public CfSignalResourceBundle() { cloudFormationSupplier = (cfSignalResourceConfig) -> { AmazonCloudFormation amazonCloudFormation = internalCloudFormation.get(); if (amazonCloudFormation != null) { return amazonCloudFormation; } return internalCloudFormation.updateAndGet((unused) -> { AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(); String awsRegion = cfSignalResourceConfig.getAwsRegion(); Region region; if (Strings.isNullOrEmpty(awsRegion)) { region = Regions.getCurrentRegion(); } else { region = Region.getRegion(Regions.fromName(awsRegion)); } amazonCloudFormationClient.setRegion(region); return amazonCloudFormationClient; }); }; } @Inject public CfSignalResourceBundle(AmazonCloudFormation amazonCloudFormation) { checkNotNull(amazonCloudFormation); cloudFormationSupplier = (config) -> amazonCloudFormation; } @Override public void initialize(Bootstrap<?> bootstrap) { } /** * Override this method to specify a {@link CfSignalResourceConfig}. Otherwise the config will be fetched from * {@linkplain T} when {@link #run(Configuration, Environment)} runs. * @return an {@link Optional} containing the config if it exists, by default {@link Optional#empty()} */ protected Optional<CfSignalResourceConfig> getConfiguration() { return Optional.empty(); } @Override public void run(T config, Environment environment) { final CfSignalResourceConfig cfSignalResourceConfig = getConfiguration().orElseGet(() -> getCfResourceBundleConfig(config)); final Optional<String> instanceId = getInstanceId(cfSignalResourceConfig); if (!instanceId.isPresent()) { LOGGER.debug("Unable to fetch EC2 Instance ID, assuming not running on AWS and thus not signalling"); return; } environment.lifecycle() .addLifeCycleListener( new CfSignalResourceLifcycleListener(cfSignalResourceConfig, instanceId.get())); } private void sendSignal(CfSignalResourceConfig config, final String instanceId, boolean success) { try { AmazonCloudFormation client = cloudFormationSupplier.apply(config); SignalResourceRequest request = new SignalResourceRequest(); request.setUniqueId(instanceId); request.setLogicalResourceId(config.getAsgResourceName()); request.setStackName(config.getStackName()); request.setStatus(success? ResourceSignalStatus.SUCCESS : ResourceSignalStatus.FAILURE); client.signalResource(request); } catch (Exception e) { LOGGER.error("There was a problem signaling " + config.getAsgResourceName() + " in stack " + config.getStackName(), e); } finally { AmazonCloudFormation internalClient = internalCloudFormation.get(); if (internalClient != null) { try { internalClient.shutdown(); } catch (Exception e) { //an internal client shouldn't affect anyone else LOGGER.debug("problem closing the internal AmazonCloudFormation client", e); } } } } private CfSignalResourceConfig getCfResourceBundleConfig(final T config) { for (Method method : config.getClass().getMethods()) { if (CfSignalResourceConfig.class.equals(method.getReturnType()) && method.getParameterCount() == 0) { try { return (CfSignalResourceConfig) method.invoke(config); } catch (IllegalAccessException e) { throw new RuntimeException("method exposing CfSignResourceConfig must be accessible", e); } catch (InvocationTargetException e) { Throwables.propagate(e); } } } throw new IllegalStateException("config must either be provided via getConfiguration() in the Application Configuration"); } private Optional<String> getInstanceId(CfSignalResourceConfig cfSignalResourceConfig) { return Optional.ofNullable( Strings.isNullOrEmpty(cfSignalResourceConfig.getEc2InstanceId()) ? EC2MetadataUtils.getInstanceId() : cfSignalResourceConfig.getEc2InstanceId()); } @VisibleForTesting /*package-private*/ AmazonCloudFormation getInternalCloudFormation() { return internalCloudFormation.get(); } @VisibleForTesting /*package-private*/ AmazonCloudFormation getCloudFormation(final CfSignalResourceConfig config) { return cloudFormationSupplier.apply(config); } @VisibleForTesting class CfSignalResourceLifcycleListener implements LifeCycle.Listener { private final CfSignalResourceConfig cfSignalResourceConfig; private final String instanceId; CfSignalResourceLifcycleListener(final CfSignalResourceConfig cfSignalResourceConfig, final String instanceId) { this.cfSignalResourceConfig = cfSignalResourceConfig; this.instanceId = instanceId; } @Override public void lifeCycleStarting(final LifeCycle event) { //dont care } @Override public void lifeCycleFailure(final LifeCycle event, final Throwable cause) { //because this method can be called if there is a failure on shutdown //only attempt to signal failure if the failure is on startup if (!(event.isStopping() || event.isStopped())) { sendSignal(cfSignalResourceConfig, instanceId, false); } } @Override public void lifeCycleStopping(final LifeCycle event) { //dont care } @Override public void lifeCycleStopped(final LifeCycle event) { //dont care } @Override public void lifeCycleStarted(final LifeCycle event) { sendSignal(cfSignalResourceConfig, instanceId, true); } } }
package net.etalia.client.domain; public class PublicationStandard extends Publication { private Media logo; private Media header; private Boolean published; private Long publishedDate; private Boolean free; private User owner; public Media getLogo() { return logo; } public void setLogo(Media logo) { this.logo = logo; } public Media getHeader() { return header; } public void setHeader(Media header) { this.header = header; } public Boolean getPublished() { return published; } public void setPublished(Boolean published) { this.published = published; } public Long getPublishedDate() { return publishedDate; } public void setPublishedDate(Long publishedDate) { this.publishedDate = publishedDate; } public Boolean getFree() { return free; } public void setFree(Boolean free) { this.free = free; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } }
package net.iponweb.disthene.reader; import com.datastax.driver.core.*; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; import org.apache.log4j.Logger; /** * @author Andrei Ivanov */ public class CassandraService { private static final String[] CASSANDRA_CPS = { "cassandra11.devops.iponweb.net", "cassandra12.devops.iponweb.net", "cassandra17.devops.iponweb.net", "cassandra18.devops.iponweb.net" }; private final static Logger logger = Logger.getLogger(Main.class); private static volatile CassandraService instance = null; private Session session; public static CassandraService getInstance() { if (instance == null) { synchronized (PathsService.class) { if (instance == null) { instance = new CassandraService(); } } } return instance; } public CassandraService() { SocketOptions socketOptions = new SocketOptions(); socketOptions.setReceiveBufferSize(8388608); socketOptions.setSendBufferSize(1048576); socketOptions.setTcpNoDelay(false); socketOptions.setReadTimeoutMillis(1000000); socketOptions.setReadTimeoutMillis(1000000); PoolingOptions poolingOptions = new PoolingOptions(); poolingOptions.setCoreConnectionsPerHost(HostDistance.REMOTE, 1024); poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, 1024); poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.REMOTE, 12000); poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 12000); poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, 512); poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, 512); poolingOptions.setMaxSimultaneousRequestsPerHostThreshold(HostDistance.REMOTE, 12000); Cluster.Builder builder = Cluster.builder() .withSocketOptions(socketOptions) .withCompression(ProtocolOptions.Compression.LZ4) .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy())) .withPoolingOptions(poolingOptions) .withProtocolVersion(ProtocolVersion.V2) .withPort(9042); for(String cp : CASSANDRA_CPS) { builder.addContactPoint(cp); } Cluster cluster = builder.build(); Metadata metadata = cluster.getMetadata(); logger.debug("Connected to cluster: " + metadata.getClusterName()); for (Host host : metadata.getAllHosts()) { logger.debug(String.format("Datacenter: %s; Host: %s; Rack: %s", host.getDatacenter(), host.getAddress(), host.getRack())); } session = cluster.connect(); } public Session getSession() { return session; } }
package net.openhft.chronicle.network; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.core.annotation.Nullable; import net.openhft.chronicle.core.io.Closeable; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.network.api.TcpHandler; import net.openhft.chronicle.network.api.session.SessionDetailsProvider; import net.openhft.chronicle.network.connection.WireOutPublisher; import net.openhft.chronicle.wire.*; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static net.openhft.chronicle.network.connection.CoreFields.reply; import static net.openhft.chronicle.wire.WriteMarshallable.EMPTY; public abstract class WireTcpHandler<T extends NetworkContext> implements TcpHandler, NetworkContextManager<T> { private static final int SIZE_OF_SIZE = 4; private static final Logger LOG = LoggerFactory.getLogger(WireTcpHandler.class); // this is the point at which it is worth doing more work to get more data. protected Wire outWire; private Wire inWire; private boolean recreateWire; @Nullable private WireType wireType; private WireOutPublisher publisher; private T nc; private volatile boolean closed; private boolean isAcceptor; public static void logYaml(final WireOut outWire) { if (YamlLogging.showServerWrites) try { LOG.info("\nServer Sends:\n" + Wires.fromSizePrefixedBlobs(outWire.bytes())); } catch (Exception e) { LOG.info("\nServer Sends ( corrupted ) :\n" + outWire.bytes().toDebugString()); } } public boolean isAcceptor() { return this.isAcceptor; } public void wireType(@NotNull WireType wireType) { this.wireType = wireType; if (publisher != null) publisher.wireType(wireType); } public WireOutPublisher publisher() { return publisher; } public void publisher(WireOutPublisher publisher) { this.publisher = publisher; if (wireType() != null) publisher.wireType(wireType()); } public void isAcceptor(boolean isAcceptor) { this.isAcceptor = isAcceptor; } @Override public void process(@NotNull Bytes in, @NotNull Bytes out) { if (closed) return; final WireType wireType = wireType(); checkWires(in, out, wireType == null ? WireType.TEXT : wireType); if (publisher != null && out.writePosition() < TcpEventHandler.TCP_BUFFER) publisher.applyAction(out); if (in.readRemaining() >= SIZE_OF_SIZE && out.writePosition() < TcpEventHandler.TCP_BUFFER) read(in, out); /*if (publisher != null && out.writePosition() < TcpEventHandler.TCP_BUFFER) publisher.applyAction(out);*/ } @Override public T nc() { return nc; } @Override public void sendHeartBeat(Bytes out, SessionDetailsProvider sessionDetails) { final WireType wireType = this.wireType; if (out.writePosition() == 0 && wireType != null) { final WireOut outWire = wireType.apply(out); outWire.writeDocument(true, w -> w.write(() -> "tid").int64(0)); outWire.writeDocument(false, w -> w.writeEventName(() -> "heartbeat").int64(Time.currentTimeMillis())); } } @Override public void onEndOfConnection(boolean heartbeatTimeOut) { publisher.close(); } /** * process all messages in this batch, provided there is plenty of output space. * * @param in the source bytes * @param out the destination bytes * @return true if we can read attempt the next */ private boolean read(@NotNull Bytes in, @NotNull Bytes out) { final long header = in.readInt(in.readPosition()); long length = Wires.lengthOf(header); assert length >= 0 && length < 1 << 23 : "length=" + length + ",in=" + in + ", hex=" + in.toHexString(); // we don't return on meta data of zero bytes as this is a system message if (length == 0 && Wires.isData(header)) { in.readSkip(SIZE_OF_SIZE); return false; } if (in.readRemaining() < length + SIZE_OF_SIZE) { // we have to first read more data before this can be processed if (LOG.isDebugEnabled()) LOG.debug(String.format("required length=%d but only got %d bytes, " + "this is short by %d bytes", length, in.readRemaining(), length - in.readRemaining())); return false; } long limit = in.readLimit(); long end = in.readPosition() + length + SIZE_OF_SIZE; assert end <= limit; long outPos = out.writePosition(); try { in.readLimit(end); final long position = inWire.bytes().readPosition(); assert inWire.bytes().readRemaining() >= length; final long wireLimit = inWire.bytes().readLimit(); try { process(inWire, outWire); } finally { try { inWire.bytes().readLimit(wireLimit); inWire.bytes().readPosition(position + length); } catch (Exception e) { //noinspection ThrowFromFinallyBlock throw new IllegalStateException("Unexpected error position: " + position + ", length: " + length + " limit(): " + inWire.bytes().readLimit(), e); } } long written = out.writePosition() - outPos; if (written > 0) return false; } catch (Throwable e) { LOG.error("", e); } finally { in.readLimit(limit); try { in.readPosition(end); } catch (Exception e) { throw new IllegalStateException("position: " + end + ", limit:" + limit + ", readLimit: " + in.readLimit() + " " + in.toDebugString(), e); } } return true; } protected void checkWires(Bytes in, Bytes out, @NotNull WireType wireType) { if (recreateWire) { recreateWire = false; inWire = wireType.apply(in); outWire = wireType.apply(out); return; } if (inWire == null) { inWire = wireType.apply(in); recreateWire = false; } if (inWire.bytes() != in) { inWire = wireType.apply(in); recreateWire = false; } if ((outWire == null || outWire.bytes() != out)) { outWire = wireType.apply(out); recreateWire = false; } } /** * Process an incoming request */ public WireType wireType() { return this.wireType; } /** * @param in the wire to be processed * @param out the result of processing the {@code in} */ protected abstract void process(@NotNull WireIn in, @NotNull WireOut out); /** * write and exceptions and rolls back if no data was written */ protected void writeData(@NotNull Bytes inBytes, @NotNull WriteMarshallable c) { outWire.writeDocument(false, out -> { final long readPosition = inBytes.readPosition(); final long position = outWire.bytes().writePosition(); try { c.writeMarshallable(outWire); } catch (Throwable t) { inBytes.readPosition(readPosition); if (LOG.isInfoEnabled()) LOG.info("While reading " + inBytes.toDebugString(), " processing wire " + c, t); outWire.bytes().writePosition(position); outWire.writeEventName(() -> "exception").throwable(t); } // write 'reply : {} ' if no data was sent if (position == outWire.bytes().writePosition()) { outWire.writeEventName(reply).marshallable(EMPTY); } }); logYaml(outWire); } /** * write and exceptions and rolls back if no data was written */ protected void writeData(boolean isNotReady, @NotNull Bytes inBytes, @NotNull WriteMarshallable c) { final WriteMarshallable marshallable = out -> { final long readPosition = inBytes.readPosition(); final long position = outWire.bytes().writePosition(); try { c.writeMarshallable(outWire); } catch (Throwable t) { inBytes.readPosition(readPosition); if (LOG.isInfoEnabled()) LOG.info("While reading " + inBytes.toDebugString(), " processing wire " + c, t); outWire.bytes().writePosition(position); outWire.writeEventName(() -> "exception").throwable(t); } // write 'reply : {} ' if no data was sent if (position == outWire.bytes().writePosition()) { outWire.writeEventName(reply).marshallable(EMPTY); } }; if (isNotReady) outWire.writeNotReadyDocument(false, marshallable); else outWire.writeDocument(false, marshallable); logYaml(outWire); } public void nc(T nc) { this.nc = nc; } @Override public void close() { closed = true; nc.connectionClosed(true); Closeable.closeQuietly(this.nc.closeTask()); } }
package net.rubygrapefruit.platform.file; import javax.annotation.CheckReturnValue; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * A handle for watching file system locations. */ @NotThreadSafe public interface FileWatcher { void startWatching(Collection<File> paths); @CheckReturnValue boolean stopWatching(Collection<File> paths); /** * Initiates an orderly shutdown and release of any native resources. * No more events will arrive after this method returns. */ void shutdown(); /** * Blocks until the termination is complete after a {@link #shutdown()} * request, or the timeout occurs, or the current thread is interrupted, * whichever happens first. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return {@code true} if this watcher terminated and * {@code false} if the timeout elapsed before termination * @throws InterruptedException if interrupted while waiting */ @CheckReturnValue boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; }
package androidsx.rateme; import android.app.Activity; import android.app.DialogFragment; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.androidsx.libraryrateme.libraryRateMe; public class HelloWorldActivity extends Activity { private Button btnRateme; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_world); setupUI(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.hello_world, menu); return super.onCreateOptionsMenu(menu); } public void setupUI (){ btnRateme = (Button) findViewById(R.id.buttonRateMe); btnRateme.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { alertMenu(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.RateMeOption: alertMenu(); break; default: break; } return super.onOptionsItemSelected(item); } public void alertMenu (){ DialogFragment dialogo = libraryRateMe.newInstance( getPackageName()); dialogo.show(getFragmentManager(), "dialog"); } }
package nl.topicus.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.RowIdLifetime; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Types; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; public class CloudSpannerDatabaseMetaData extends AbstractCloudSpannerDatabaseMetaData { private static final int JDBC_MAJOR_VERSION = 4; private static final int JDBC_MINOR_VERSION = 2; private static final String FROM_STATEMENT_WITHOUT_RESULTS = " FROM INFORMATION_SCHEMA.TABLES T WHERE 1=2 "; private static final String VERSION_AND_IDENTIFIER_COLUMNS_SELECT_STATEMENT = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, 0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN "; private CloudSpannerConnection connection; CloudSpannerDatabaseMetaData(CloudSpannerConnection connection) { this.connection = connection; } @Override public boolean allProceduresAreCallable() throws SQLException { return true; } @Override public boolean allTablesAreSelectable() throws SQLException { return true; } @Override public String getURL() throws SQLException { return connection.getUrl(); } @Override public String getUserName() throws SQLException { return connection.getClientId(); } @Override public boolean isReadOnly() throws SQLException { return false; } @Override public boolean nullsAreSortedHigh() throws SQLException { return false; } @Override public boolean nullsAreSortedLow() throws SQLException { return true; } @Override public boolean nullsAreSortedAtStart() throws SQLException { return true; } @Override public boolean nullsAreSortedAtEnd() throws SQLException { return false; } @Override public String getDatabaseProductName() throws SQLException { return connection.getProductName(); } @Override public String getDatabaseProductVersion() throws SQLException { return getDatabaseMajorVersion() + "." + getDatabaseMinorVersion(); } @Override public String getDriverName() throws SQLException { return CloudSpannerDriver.class.getName(); } @Override public String getDriverVersion() throws SQLException { return getDriverMajorVersion() + "." + getDriverMinorVersion(); } @Override public int getDriverMajorVersion() { return CloudSpannerDriver.MAJOR_VERSION; } @Override public int getDriverMinorVersion() { return CloudSpannerDriver.MINOR_VERSION; } @Override public boolean usesLocalFiles() throws SQLException { return false; } @Override public boolean usesLocalFilePerTable() throws SQLException { return false; } @Override public boolean supportsMixedCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseIdentifiers() throws SQLException { return true; } @Override public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { return true; } @Override public String getIdentifierQuoteString() throws SQLException { return "`"; } @Override public String getSQLKeywords() throws SQLException { return "INTERLEAVE, PARENT"; } @Override public String getNumericFunctions() throws SQLException { return ""; } @Override public String getStringFunctions() throws SQLException { return ""; } @Override public String getSystemFunctions() throws SQLException { return ""; } @Override public String getTimeDateFunctions() throws SQLException { return ""; } @Override public String getSearchStringEscape() throws SQLException { return "\\"; } @Override public String getExtraNameCharacters() throws SQLException { return ""; } @Override public boolean supportsAlterTableWithAddColumn() throws SQLException { return true; } @Override public boolean supportsAlterTableWithDropColumn() throws SQLException { return true; } @Override public boolean supportsColumnAliasing() throws SQLException { return true; } @Override public boolean nullPlusNonNullIsNull() throws SQLException { return true; } @Override public boolean supportsConvert() throws SQLException { return false; } @Override public boolean supportsConvert(int fromType, int toType) throws SQLException { return false; } @Override public boolean supportsTableCorrelationNames() throws SQLException { return true; } @Override public boolean supportsDifferentTableCorrelationNames() throws SQLException { return false; } @Override public boolean supportsExpressionsInOrderBy() throws SQLException { return true; } @Override public boolean supportsOrderByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupBy() throws SQLException { return true; } @Override public boolean supportsGroupByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupByBeyondSelect() throws SQLException { return true; } @Override public boolean supportsLikeEscapeClause() throws SQLException { return true; } @Override public boolean supportsMultipleResultSets() throws SQLException { return true; } @Override public boolean supportsMultipleTransactions() throws SQLException { return true; } @Override public boolean supportsNonNullableColumns() throws SQLException { return true; } @Override public boolean supportsMinimumSQLGrammar() throws SQLException { return false; } @Override public boolean supportsCoreSQLGrammar() throws SQLException { return false; } @Override public boolean supportsExtendedSQLGrammar() throws SQLException { return false; } @Override public boolean supportsANSI92EntryLevelSQL() throws SQLException { return false; } @Override public boolean supportsANSI92IntermediateSQL() throws SQLException { return false; } @Override public boolean supportsANSI92FullSQL() throws SQLException { return false; } @Override public boolean supportsIntegrityEnhancementFacility() throws SQLException { return false; } @Override public boolean supportsOuterJoins() throws SQLException { return true; } @Override public boolean supportsFullOuterJoins() throws SQLException { return true; } @Override public boolean supportsLimitedOuterJoins() throws SQLException { return true; } @Override public String getSchemaTerm() throws SQLException { return null; } @Override public String getProcedureTerm() throws SQLException { return null; } @Override public String getCatalogTerm() throws SQLException { return null; } @Override public boolean isCatalogAtStart() throws SQLException { return false; } @Override public String getCatalogSeparator() throws SQLException { return null; } @Override public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } @Override public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } @Override public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsPositionedDelete() throws SQLException { return false; } @Override public boolean supportsPositionedUpdate() throws SQLException { return false; } @Override public boolean supportsSelectForUpdate() throws SQLException { return false; } @Override public boolean supportsStoredProcedures() throws SQLException { return false; } @Override public boolean supportsSubqueriesInComparisons() throws SQLException { return true; } @Override public boolean supportsSubqueriesInExists() throws SQLException { return true; } @Override public boolean supportsSubqueriesInIns() throws SQLException { return true; } @Override public boolean supportsSubqueriesInQuantifieds() throws SQLException { return true; } @Override public boolean supportsCorrelatedSubqueries() throws SQLException { return true; } @Override public boolean supportsUnion() throws SQLException { return true; } @Override public boolean supportsUnionAll() throws SQLException { return true; } @Override public boolean supportsOpenCursorsAcrossCommit() throws SQLException { return false; } @Override public boolean supportsOpenCursorsAcrossRollback() throws SQLException { return false; } @Override public boolean supportsOpenStatementsAcrossCommit() throws SQLException { return true; } @Override public boolean supportsOpenStatementsAcrossRollback() throws SQLException { return true; } @Override public int getMaxBinaryLiteralLength() throws SQLException { return 0; } @Override public int getMaxCharLiteralLength() throws SQLException { return 0; } @Override public int getMaxColumnNameLength() throws SQLException { return 128; } @Override public int getMaxColumnsInGroupBy() throws SQLException { return 0; } @Override public int getMaxColumnsInIndex() throws SQLException { return 16; } @Override public int getMaxColumnsInOrderBy() throws SQLException { return 0; } @Override public int getMaxColumnsInSelect() throws SQLException { return 0; } @Override public int getMaxColumnsInTable() throws SQLException { return 1024; } /** * Limit is 10,000 per database per node */ @Override public int getMaxConnections() throws SQLException { return connection.getNodeCount() * 10000; } @Override public int getMaxCursorNameLength() throws SQLException { return 0; } @Override public int getMaxIndexLength() throws SQLException { return 8000; } @Override public int getMaxSchemaNameLength() throws SQLException { return 0; } @Override public int getMaxProcedureNameLength() throws SQLException { return 0; } @Override public int getMaxCatalogNameLength() throws SQLException { return 0; } @Override public int getMaxRowSize() throws SQLException { return 1024 * 10000000; } @Override public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { return true; } @Override public int getMaxStatementLength() throws SQLException { return 1000000; } @Override public int getMaxStatements() throws SQLException { return 0; } @Override public int getMaxTableNameLength() throws SQLException { return 128; } @Override public int getMaxTablesInSelect() throws SQLException { return 0; } @Override public int getMaxUserNameLength() throws SQLException { return 0; } @Override public int getDefaultTransactionIsolation() throws SQLException { return Connection.TRANSACTION_SERIALIZABLE; } @Override public boolean supportsTransactions() throws SQLException { return true; } @Override public boolean supportsTransactionIsolationLevel(int level) throws SQLException { return Connection.TRANSACTION_SERIALIZABLE == level; } @Override public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { return false; } @Override public boolean supportsDataManipulationTransactionsOnly() throws SQLException { return false; } @Override public boolean dataDefinitionCausesTransactionCommit() throws SQLException { return false; } @Override public boolean dataDefinitionIgnoredInTransactions() throws SQLException { return false; } @Override public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, NULL AS RES1, NULL AS RES2, NULL AS RES3, " + "'' AS REMARKS, 0 AS PROCEDURE_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, " + "0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, " + "0 AS NULLABLE, '' AS REMARKS, '' AS COLUMN_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATATIME_SUB, " + "0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } private CloudSpannerPreparedStatement prepareStatement(String sql, String... params) throws SQLException { CloudSpannerPreparedStatement statement = connection.prepareStatement(sql); statement.setForceSingleUseReadContext(true); int paramIndex = 1; for (String param : params) { if (param != null) { statement.setString(paramIndex, param.toUpperCase()); paramIndex++; } } return statement; } private String getCatalogSchemaTableWhereClause(String alias, String catalog, String schema, String table) { StringBuilder res = new StringBuilder(); if (catalog != null) res.append(String.format("AND UPPER(%s.TABLE_CATALOG) like ? ", alias)); if (schema != null) res.append(String.format("AND UPPER(%s.TABLE_SCHEMA) like ? ", alias)); if (table != null) res.append(String.format("AND UPPER(%s.TABLE_NAME) like ? ", alias)); return res.toString(); } @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.SELECT_TABLES_COLUMNS + CloudSpannerDatabaseMetaDataConstants.FROM_TABLES_T + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; sql = sql + getCatalogSchemaTableWhereClause("T", catalog, schemaPattern, tableNamePattern); sql = sql + "ORDER BY TABLE_NAME"; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern); return statement.executeQuery(); } @Override public ResultSet getSchemas() throws SQLException { return getSchemas(null, null); } @Override public ResultSet getCatalogs() throws SQLException { String sql = "SELECT '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTableTypes() throws SQLException { String sql = "SELECT 'TABLE' AS TABLE_TYPE"; return prepareStatement(sql).executeQuery(); } @Override public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_COLUMNS; sql = sql + getCatalogSchemaTableWhereClause("C", catalog, schemaPattern, tableNamePattern); if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS COLUMN_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { return getVersionColumnsOrBestRowIdentifier(); } @Override public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { return getVersionColumnsOrBestRowIdentifier(); } /** * A simple private method that combines the result of two methods that * return exactly the same result * * @return An empty {@link ResultSet} containing the columns for the methods * {@link DatabaseMetaData#getBestRowIdentifier(String, String, String, int, boolean)} * and * {@link DatabaseMetaData#getVersionColumns(String, String, String)} * @throws SQLException */ private ResultSet getVersionColumnsOrBestRowIdentifier() throws SQLException { String sql = VERSION_AND_IDENTIFIER_COLUMNS_SELECT_STATEMENT + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT IDX.TABLE_CATALOG AS TABLE_CAT, IDX.TABLE_SCHEMA AS TABLE_SCHEM, IDX.TABLE_NAME AS TABLE_NAME, COLS.COLUMN_NAME AS COLUMN_NAME, ORDINAL_POSITION AS KEY_SEQ, IDX.INDEX_NAME AS PK_NAME " + "FROM INFORMATION_SCHEMA.INDEXES IDX " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COLS ON IDX.TABLE_CATALOG=COLS.TABLE_CATALOG AND IDX.TABLE_SCHEMA=COLS.TABLE_SCHEMA AND IDX.TABLE_NAME=COLS.TABLE_NAME AND IDX.INDEX_NAME=COLS.INDEX_NAME " + "WHERE IDX.INDEX_TYPE='PRIMARY_KEY' "; sql = sql + getCatalogSchemaTableWhereClause("IDX", catalog, schema, table); sql = sql + "ORDER BY COLS.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT PARENT.TABLE_CATALOG AS PKTABLE_CAT, PARENT.TABLE_SCHEMA AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, COL.COLUMN_NAME AS PKCOLUMN_NAME, CHILD.TABLE_CATALOG AS FKTABLE_CAT, CHILD.TABLE_SCHEMA AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, COL.COLUMN_NAME FKCOLUMN_NAME, COL.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION = 'CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, NULL AS FK_NAME, INDEXES.INDEX_NAME AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES CHILD " + "INNER JOIN INFORMATION_SCHEMA.TABLES PARENT ON CHILD.TABLE_CATALOG=PARENT.TABLE_CATALOG AND CHILD.TABLE_SCHEMA=PARENT.TABLE_SCHEMA AND CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEXES ON PARENT.TABLE_CATALOG=INDEXES.TABLE_CATALOG AND PARENT.TABLE_SCHEMA=INDEXES.TABLE_SCHEMA AND PARENT.TABLE_NAME=INDEXES.TABLE_NAME AND INDEXES.INDEX_TYPE='PRIMARY_KEY' " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COL ON INDEXES.TABLE_CATALOG=COL.TABLE_CATALOG AND INDEXES.TABLE_SCHEMA=COL.TABLE_SCHEMA AND INDEXES.TABLE_NAME=COL.TABLE_NAME AND INDEXES.INDEX_NAME=COL.INDEX_NAME " + "WHERE CHILD.PARENT_TABLE_NAME IS NOT NULL "; sql = sql + getCatalogSchemaTableWhereClause("CHILD", catalog, schema, table); sql = sql + "ORDER BY PARENT.TABLE_CATALOG, PARENT.TABLE_SCHEMA, PARENT.TABLE_NAME, COL.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT " + "NULL AS PKTABLE_CAT, NULL AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS PKCOLUMN_NAME, " + "NULL AS FKTABLE_CAT, NULL AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS FKCOLUMN_NAME, " + "PARENT_INDEX_COLUMNS.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION='CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, " + "NULL AS FK_NAME, 'PRIMARY_KEY' AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES PARENT " + "INNER JOIN INFORMATION_SCHEMA.TABLES CHILD ON CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS PARENT_INDEX_COLUMNS ON PARENT_INDEX_COLUMNS.TABLE_NAME=PARENT.TABLE_NAME AND PARENT_INDEX_COLUMNS.INDEX_NAME='PRIMARY_KEY' " + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; sql = sql + getCatalogSchemaTableWhereClause("PARENT", catalog, schema, table); sql = sql + "ORDER BY CHILD.TABLE_CATALOG, CHILD.TABLE_SCHEMA, CHILD.TABLE_NAME, PARENT_INDEX_COLUMNS.ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public ResultSet getTypeInfo() throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_TYPE_INFO; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { return getIndexInfo(catalog, schema, table, null, unique); } public ResultSet getIndexInfo(String catalog, String schema, String indexName) throws SQLException { return getIndexInfo(catalog, schema, null, indexName, false); } private ResultSet getIndexInfo(String catalog, String schema, String table, String indexName, boolean unique) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_INDEX_INFO; sql = sql + getCatalogSchemaTableWhereClause("IDX", catalog, schema, table); if (unique) sql = sql + "AND IS_UNIQUE=TRUE "; if (indexName != null) sql = sql + " AND UPPER(IDX.INDEX_NAME) LIKE ? "; sql = sql + "ORDER BY IS_UNIQUE, IDX.INDEX_NAME, ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table, indexName); return statement.executeQuery(); } @Override public boolean supportsResultSetType(int type) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY; } @Override public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY; } @Override public boolean ownUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean othersUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean updatesAreDetected(int type) throws SQLException { return false; } @Override public boolean deletesAreDetected(int type) throws SQLException { return false; } @Override public boolean insertsAreDetected(int type) throws SQLException { return false; } @Override public boolean supportsBatchUpdates() throws SQLException { return true; } @Override public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_UDTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public Connection getConnection() throws SQLException { return connection; } @Override public boolean supportsSavepoints() throws SQLException { return true; } @Override public boolean supportsNamedParameters() throws SQLException { return false; } @Override public boolean supportsMultipleOpenResults() throws SQLException { return false; } @Override public boolean supportsGetGeneratedKeys() throws SQLException { return false; } @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { String sql = "SELECT * FROM (SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, " + "'' AS SUPERTYPE_CAT, '' AS SUPERTYPE_SCHEM, '' AS SUPERTYPE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS + ") T"; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT * FROM (SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS SUPERTABLE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS + ") T"; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { String sql = "SELECT * FROM (SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, '' AS ATTR_NAME, 0 AS DATA_TYPE, " + "'' AS ATTR_TYPE_NAME, 0 AS ATTR_SIZE, 0 AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 0 AS NULLABLE, " + "'' AS REMARKS, '' AS ATTR_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATETIME_SUB, 0 AS CHAR_OCTET_LENGTH, " + "0 AS ORDINAL_POSITION, 'NO' AS IS_NULLABLE, '' AS SCOPE_CATALOG, '' AS SCOPE_SCHEMA, '' AS SCOPE_TABLE, " + "0 AS SOURCE_DATA_TYPE " + FROM_STATEMENT_WITHOUT_RESULTS + ") T"; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public boolean supportsResultSetHoldability(int holdability) throws SQLException { return holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT; } @Override public int getResultSetHoldability() throws SQLException { return ResultSet.HOLD_CURSORS_OVER_COMMIT; } @Override public int getDatabaseMajorVersion() throws SQLException { return connection.getSimulateMajorVersion() == null ? 1 : connection.getSimulateMajorVersion(); } @Override public int getDatabaseMinorVersion() throws SQLException { return connection.getSimulateMinorVersion() == null ? 0 : connection.getSimulateMinorVersion(); } @Override public int getJDBCMajorVersion() throws SQLException { return JDBC_MAJOR_VERSION; } @Override public int getJDBCMinorVersion() throws SQLException { return JDBC_MINOR_VERSION; } @Override public int getSQLStateType() throws SQLException { return sqlStateSQL; } @Override public boolean locatorsUpdateCopy() throws SQLException { return true; } @Override public boolean supportsStatementPooling() throws SQLException { return false; } @Override public RowIdLifetime getRowIdLifetime() throws SQLException { return RowIdLifetime.ROWID_UNSUPPORTED; } @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { String sql = "SELECT SCHEMA_NAME AS TABLE_SCHEM, CATALOG_NAME AS TABLE_CATALOG FROM INFORMATION_SCHEMA.SCHEMATA " + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(CATALOG_NAME) like ? "; if (schemaPattern != null) sql = sql + "AND UPPER(SCHEMA_NAME) like ? "; sql = sql + "ORDER BY SCHEMA_NAME"; PreparedStatement statement = prepareStatement(sql, catalog, schemaPattern); return statement.executeQuery(); } @Override public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { return false; } @Override public boolean autoCommitFailureClosesAllResultSets() throws SQLException { return false; } @Override public ResultSet getClientInfoProperties() throws SQLException { String sql = "SELECT * FROM (SELECT '' AS NAME, 0 AS MAX_LEN, '' AS DEFAULT_VALUE, '' AS DESCRIPTION " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + ") T ORDER BY NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { String sql = "SELECT * FROM (SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS REMARKS, 0 AS FUNCTION_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + ") T ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT * FROM (SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, 1111 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, 0 AS NULLABLE, '' AS REMARKS, 0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + ") T ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT * FROM (select TABLE_CATALOG AS TABLE_CAT, TABLE_SCHEMA AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, " + "CASE " + " WHEN SPANNER_TYPE = 'ARRAY' THEN " + Types.ARRAY + " " + " WHEN SPANNER_TYPE = 'BOOL' THEN " + Types.BOOLEAN + " " + " WHEN SPANNER_TYPE = 'BYTES' THEN " + Types.BINARY + " " + " WHEN SPANNER_TYPE = 'DATE' THEN " + Types.DATE + " " + " WHEN SPANNER_TYPE = 'FLOAT64' THEN " + Types.DOUBLE + " " + " WHEN SPANNER_TYPE = 'INT64' THEN " + Types.BIGINT + " " + " WHEN SPANNER_TYPE = 'STRING' THEN " + Types.NVARCHAR + " " + " WHEN SPANNER_TYPE = 'STRUCT' THEN " + Types.STRUCT + " " + " WHEN SPANNER_TYPE = 'TIMESTAMP' THEN " + Types.TIMESTAMP + " " + "END AS DATA_TYPE, " + "0 AS COLUMN_SIZE, NULL AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 'USAGE_UNKNOWN' AS COLUMN_USAGE, NULL AS REMARKS, 0 AS CHAR_OCTET_LENGTH, IS_NULLABLE " + FROM_STATEMENT_WITHOUT_RESULTS + ") T "; sql = sql + getCatalogSchemaTableWhereClause("T", catalog, schemaPattern, tableNamePattern); if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public boolean generatedKeyAlwaysReturned() throws SQLException { return false; } }
package nl.topicus.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.RowIdLifetime; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Types; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; public class CloudSpannerDatabaseMetaData extends AbstractCloudSpannerDatabaseMetaData { private static final int JDBC_MAJOR_VERSION = 4; private static final int JDBC_MINOR_VERSION = 2; private static final String FROM_STATEMENT_WITHOUT_RESULTS = " FROM INFORMATION_SCHEMA.TABLES T WHERE 1=2 "; private static final String VERSION_AND_IDENTIFIER_COLUMNS_SELECT_STATEMENT = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, 0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN "; private CloudSpannerConnection connection; CloudSpannerDatabaseMetaData(CloudSpannerConnection connection) { this.connection = connection; } @Override public boolean allProceduresAreCallable() throws SQLException { return true; } @Override public boolean allTablesAreSelectable() throws SQLException { return true; } @Override public String getURL() throws SQLException { return connection.getUrl(); } @Override public String getUserName() throws SQLException { return connection.getClientId(); } @Override public boolean isReadOnly() throws SQLException { return false; } @Override public boolean nullsAreSortedHigh() throws SQLException { return false; } @Override public boolean nullsAreSortedLow() throws SQLException { return true; } @Override public boolean nullsAreSortedAtStart() throws SQLException { return true; } @Override public boolean nullsAreSortedAtEnd() throws SQLException { return false; } @Override public String getDatabaseProductName() throws SQLException { return connection.getProductName(); } @Override public String getDatabaseProductVersion() throws SQLException { return getDatabaseMajorVersion() + "." + getDatabaseMinorVersion(); } @Override public String getDriverName() throws SQLException { return CloudSpannerDriver.class.getName(); } @Override public String getDriverVersion() throws SQLException { return getDriverMajorVersion() + "." + getDriverMinorVersion(); } @Override public int getDriverMajorVersion() { return CloudSpannerDriver.MAJOR_VERSION; } @Override public int getDriverMinorVersion() { return CloudSpannerDriver.MINOR_VERSION; } @Override public boolean usesLocalFiles() throws SQLException { return false; } @Override public boolean usesLocalFilePerTable() throws SQLException { return false; } @Override public boolean supportsMixedCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseIdentifiers() throws SQLException { return true; } @Override public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { return true; } @Override public String getIdentifierQuoteString() throws SQLException { return "`"; } @Override public String getSQLKeywords() throws SQLException { return "INTERLEAVE, PARENT"; } @Override public String getNumericFunctions() throws SQLException { return ""; } @Override public String getStringFunctions() throws SQLException { return ""; } @Override public String getSystemFunctions() throws SQLException { return ""; } @Override public String getTimeDateFunctions() throws SQLException { return ""; } @Override public String getSearchStringEscape() throws SQLException { return "\\"; } @Override public String getExtraNameCharacters() throws SQLException { return ""; } @Override public boolean supportsAlterTableWithAddColumn() throws SQLException { return true; } @Override public boolean supportsAlterTableWithDropColumn() throws SQLException { return true; } @Override public boolean supportsColumnAliasing() throws SQLException { return true; } @Override public boolean nullPlusNonNullIsNull() throws SQLException { return true; } @Override public boolean supportsConvert() throws SQLException { return false; } @Override public boolean supportsConvert(int fromType, int toType) throws SQLException { return false; } @Override public boolean supportsTableCorrelationNames() throws SQLException { return true; } @Override public boolean supportsDifferentTableCorrelationNames() throws SQLException { return false; } @Override public boolean supportsExpressionsInOrderBy() throws SQLException { return true; } @Override public boolean supportsOrderByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupBy() throws SQLException { return true; } @Override public boolean supportsGroupByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupByBeyondSelect() throws SQLException { return true; } @Override public boolean supportsLikeEscapeClause() throws SQLException { return true; } @Override public boolean supportsMultipleResultSets() throws SQLException { return true; } @Override public boolean supportsMultipleTransactions() throws SQLException { return true; } @Override public boolean supportsNonNullableColumns() throws SQLException { return true; } @Override public boolean supportsMinimumSQLGrammar() throws SQLException { return false; } @Override public boolean supportsCoreSQLGrammar() throws SQLException { return false; } @Override public boolean supportsExtendedSQLGrammar() throws SQLException { return false; } @Override public boolean supportsANSI92EntryLevelSQL() throws SQLException { return false; } @Override public boolean supportsANSI92IntermediateSQL() throws SQLException { return false; } @Override public boolean supportsANSI92FullSQL() throws SQLException { return false; } @Override public boolean supportsIntegrityEnhancementFacility() throws SQLException { return false; } @Override public boolean supportsOuterJoins() throws SQLException { return true; } @Override public boolean supportsFullOuterJoins() throws SQLException { return true; } @Override public boolean supportsLimitedOuterJoins() throws SQLException { return true; } @Override public String getSchemaTerm() throws SQLException { return null; } @Override public String getProcedureTerm() throws SQLException { return null; } @Override public String getCatalogTerm() throws SQLException { return null; } @Override public boolean isCatalogAtStart() throws SQLException { return false; } @Override public String getCatalogSeparator() throws SQLException { return null; } @Override public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } @Override public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } @Override public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsPositionedDelete() throws SQLException { return false; } @Override public boolean supportsPositionedUpdate() throws SQLException { return false; } @Override public boolean supportsSelectForUpdate() throws SQLException { return false; } @Override public boolean supportsStoredProcedures() throws SQLException { return false; } @Override public boolean supportsSubqueriesInComparisons() throws SQLException { return true; } @Override public boolean supportsSubqueriesInExists() throws SQLException { return true; } @Override public boolean supportsSubqueriesInIns() throws SQLException { return true; } @Override public boolean supportsSubqueriesInQuantifieds() throws SQLException { return true; } @Override public boolean supportsCorrelatedSubqueries() throws SQLException { return true; } @Override public boolean supportsUnion() throws SQLException { return true; } @Override public boolean supportsUnionAll() throws SQLException { return true; } @Override public boolean supportsOpenCursorsAcrossCommit() throws SQLException { return false; } @Override public boolean supportsOpenCursorsAcrossRollback() throws SQLException { return false; } @Override public boolean supportsOpenStatementsAcrossCommit() throws SQLException { return true; } @Override public boolean supportsOpenStatementsAcrossRollback() throws SQLException { return true; } @Override public int getMaxBinaryLiteralLength() throws SQLException { return 0; } @Override public int getMaxCharLiteralLength() throws SQLException { return 0; } @Override public int getMaxColumnNameLength() throws SQLException { return 128; } @Override public int getMaxColumnsInGroupBy() throws SQLException { return 0; } @Override public int getMaxColumnsInIndex() throws SQLException { return 16; } @Override public int getMaxColumnsInOrderBy() throws SQLException { return 0; } @Override public int getMaxColumnsInSelect() throws SQLException { return 0; } @Override public int getMaxColumnsInTable() throws SQLException { return 1024; } /** * Limit is 10,000 per database per node */ @Override public int getMaxConnections() throws SQLException { return connection.getNodeCount() * 10000; } @Override public int getMaxCursorNameLength() throws SQLException { return 0; } @Override public int getMaxIndexLength() throws SQLException { return 8000; } @Override public int getMaxSchemaNameLength() throws SQLException { return 0; } @Override public int getMaxProcedureNameLength() throws SQLException { return 0; } @Override public int getMaxCatalogNameLength() throws SQLException { return 0; } @Override public int getMaxRowSize() throws SQLException { return 1024 * 10000000; } @Override public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { return true; } @Override public int getMaxStatementLength() throws SQLException { return 1000000; } @Override public int getMaxStatements() throws SQLException { return 0; } @Override public int getMaxTableNameLength() throws SQLException { return 128; } @Override public int getMaxTablesInSelect() throws SQLException { return 0; } @Override public int getMaxUserNameLength() throws SQLException { return 0; } @Override public int getDefaultTransactionIsolation() throws SQLException { return Connection.TRANSACTION_SERIALIZABLE; } @Override public boolean supportsTransactions() throws SQLException { return true; } @Override public boolean supportsTransactionIsolationLevel(int level) throws SQLException { return Connection.TRANSACTION_SERIALIZABLE == level; } @Override public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { return false; } @Override public boolean supportsDataManipulationTransactionsOnly() throws SQLException { return false; } @Override public boolean dataDefinitionCausesTransactionCommit() throws SQLException { return false; } @Override public boolean dataDefinitionIgnoredInTransactions() throws SQLException { return false; } @Override public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, NULL AS RES1, NULL AS RES2, NULL AS RES3, " + "'' AS REMARKS, 0 AS PROCEDURE_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, " + "0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, " + "0 AS NULLABLE, '' AS REMARKS, '' AS COLUMN_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATATIME_SUB, " + "0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } private CloudSpannerPreparedStatement prepareStatement(String sql, String... params) throws SQLException { CloudSpannerPreparedStatement statement = connection.prepareStatement(sql); statement.setForceSingleUseReadContext(true); int paramIndex = 1; for (String param : params) { if (param != null) { statement.setString(paramIndex, param.toUpperCase()); paramIndex++; } } return statement; } private String getCatalogSchemaTableWhereClause(String alias, String catalog, String schema, String table) { StringBuilder res = new StringBuilder(); if (catalog != null) res.append(String.format("AND UPPER(%s.TABLE_CATALOG) like ? ", alias)); if (schema != null) res.append(String.format("AND UPPER(%s.TABLE_SCHEMA) like ? ", alias)); if (table != null) res.append(String.format("AND UPPER(%s.TABLE_NAME) like ? ", alias)); return res.toString(); } @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.SELECT_TABLES_COLUMNS + CloudSpannerDatabaseMetaDataConstants.FROM_TABLES_T + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; sql = sql + getCatalogSchemaTableWhereClause("T", catalog, schemaPattern, tableNamePattern); sql = sql + "ORDER BY TABLE_NAME"; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern); return statement.executeQuery(); } @Override public ResultSet getSchemas() throws SQLException { return getSchemas(null, null); } @Override public ResultSet getCatalogs() throws SQLException { String sql = "SELECT '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTableTypes() throws SQLException { String sql = "SELECT 'TABLE' AS TABLE_TYPE"; return prepareStatement(sql).executeQuery(); } @Override public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_COLUMNS; sql = sql + getCatalogSchemaTableWhereClause("C", catalog, schemaPattern, tableNamePattern); if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS COLUMN_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { return getVersionColumnsOrBestRowIdentifier(); } @Override public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { return getVersionColumnsOrBestRowIdentifier(); } /** * A simple private method that combines the result of two methods that * return exactly the same result * * @return An empty {@link ResultSet} containing the columns for the methods * {@link DatabaseMetaData#getBestRowIdentifier(String, String, String, int, boolean)} * and * {@link DatabaseMetaData#getVersionColumns(String, String, String)} * @throws SQLException */ private ResultSet getVersionColumnsOrBestRowIdentifier() throws SQLException { String sql = VERSION_AND_IDENTIFIER_COLUMNS_SELECT_STATEMENT + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT IDX.TABLE_CATALOG AS TABLE_CAT, IDX.TABLE_SCHEMA AS TABLE_SCHEM, IDX.TABLE_NAME AS TABLE_NAME, COLS.COLUMN_NAME AS COLUMN_NAME, ORDINAL_POSITION AS KEY_SEQ, IDX.INDEX_NAME AS PK_NAME " + "FROM INFORMATION_SCHEMA.INDEXES IDX " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COLS ON IDX.TABLE_CATALOG=COLS.TABLE_CATALOG AND IDX.TABLE_SCHEMA=COLS.TABLE_SCHEMA AND IDX.TABLE_NAME=COLS.TABLE_NAME AND IDX.INDEX_NAME=COLS.INDEX_NAME " + "WHERE IDX.INDEX_TYPE='PRIMARY_KEY' "; sql = sql + getCatalogSchemaTableWhereClause("IDX", catalog, schema, table); sql = sql + "ORDER BY COLS.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT PARENT.TABLE_CATALOG AS PKTABLE_CAT, PARENT.TABLE_SCHEMA AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, COL.COLUMN_NAME AS PKCOLUMN_NAME, CHILD.TABLE_CATALOG AS FKTABLE_CAT, CHILD.TABLE_SCHEMA AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, COL.COLUMN_NAME FKCOLUMN_NAME, COL.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION = 'CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, NULL AS FK_NAME, INDEXES.INDEX_NAME AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES CHILD " + "INNER JOIN INFORMATION_SCHEMA.TABLES PARENT ON CHILD.TABLE_CATALOG=PARENT.TABLE_CATALOG AND CHILD.TABLE_SCHEMA=PARENT.TABLE_SCHEMA AND CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEXES ON PARENT.TABLE_CATALOG=INDEXES.TABLE_CATALOG AND PARENT.TABLE_SCHEMA=INDEXES.TABLE_SCHEMA AND PARENT.TABLE_NAME=INDEXES.TABLE_NAME AND INDEXES.INDEX_TYPE='PRIMARY_KEY' " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COL ON INDEXES.TABLE_CATALOG=COL.TABLE_CATALOG AND INDEXES.TABLE_SCHEMA=COL.TABLE_SCHEMA AND INDEXES.TABLE_NAME=COL.TABLE_NAME AND INDEXES.INDEX_NAME=COL.INDEX_NAME " + "WHERE CHILD.PARENT_TABLE_NAME IS NOT NULL "; sql = sql + getCatalogSchemaTableWhereClause("CHILD", catalog, schema, table); sql = sql + "ORDER BY PARENT.TABLE_CATALOG, PARENT.TABLE_SCHEMA, PARENT.TABLE_NAME, COL.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT " + "NULL AS PKTABLE_CAT, NULL AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS PKCOLUMN_NAME, " + "NULL AS FKTABLE_CAT, NULL AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS FKCOLUMN_NAME, " + "PARENT_INDEX_COLUMNS.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION='CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, " + "NULL AS FK_NAME, 'PRIMARY_KEY' AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES PARENT " + "INNER JOIN INFORMATION_SCHEMA.TABLES CHILD ON CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS PARENT_INDEX_COLUMNS ON PARENT_INDEX_COLUMNS.TABLE_NAME=PARENT.TABLE_NAME AND PARENT_INDEX_COLUMNS.INDEX_NAME='PRIMARY_KEY' " + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; sql = sql + getCatalogSchemaTableWhereClause("PARENT", catalog, schema, table); sql = sql + "ORDER BY CHILD.TABLE_CATALOG, CHILD.TABLE_SCHEMA, CHILD.TABLE_NAME, PARENT_INDEX_COLUMNS.ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public ResultSet getTypeInfo() throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_TYPE_INFO; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { return getIndexInfo(catalog, schema, table, null, unique); } public ResultSet getIndexInfo(String catalog, String schema, String indexName) throws SQLException { return getIndexInfo(catalog, schema, null, indexName, false); } private ResultSet getIndexInfo(String catalog, String schema, String table, String indexName, boolean unique) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_INDEX_INFO; sql = sql + getCatalogSchemaTableWhereClause("IDX", catalog, schema, table); if (unique) sql = sql + "AND IS_UNIQUE=TRUE "; if (indexName != null) sql = sql + " AND UPPER(IDX.INDEX_NAME) LIKE ? "; sql = sql + "ORDER BY IS_UNIQUE, INDEX_NAME, ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table, indexName); return statement.executeQuery(); } @Override public boolean supportsResultSetType(int type) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY; } @Override public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY; } @Override public boolean ownUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean othersUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean updatesAreDetected(int type) throws SQLException { return false; } @Override public boolean deletesAreDetected(int type) throws SQLException { return false; } @Override public boolean insertsAreDetected(int type) throws SQLException { return false; } @Override public boolean supportsBatchUpdates() throws SQLException { return true; } @Override public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { String sql = CloudSpannerDatabaseMetaDataConstants.GET_UDTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public Connection getConnection() throws SQLException { return connection; } @Override public boolean supportsSavepoints() throws SQLException { return true; } @Override public boolean supportsNamedParameters() throws SQLException { return false; } @Override public boolean supportsMultipleOpenResults() throws SQLException { return false; } @Override public boolean supportsGetGeneratedKeys() throws SQLException { return false; } @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, " + "'' AS SUPERTYPE_CAT, '' AS SUPERTYPE_SCHEM, '' AS SUPERTYPE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS SUPERTABLE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, '' AS ATTR_NAME, 0 AS DATA_TYPE, " + "'' AS ATTR_TYPE_NAME, 0 AS ATTR_SIZE, 0 AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 0 AS NULLABLE, " + "'' AS REMARKS, '' AS ATTR_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATETIME_SUB, 0 AS CHAR_OCTET_LENGTH, " + "0 AS ORDINAL_POSITION, 'NO' AS IS_NULLABLE, '' AS SCOPE_CATALOG, '' AS SCOPE_SCHEMA, '' AS SCOPE_TABLE, " + "0 AS SOURCE_DATA_TYPE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public boolean supportsResultSetHoldability(int holdability) throws SQLException { return holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT; } @Override public int getResultSetHoldability() throws SQLException { return ResultSet.HOLD_CURSORS_OVER_COMMIT; } @Override public int getDatabaseMajorVersion() throws SQLException { return connection.getSimulateMajorVersion() == null ? 1 : connection.getSimulateMajorVersion(); } @Override public int getDatabaseMinorVersion() throws SQLException { return connection.getSimulateMinorVersion() == null ? 0 : connection.getSimulateMinorVersion(); } @Override public int getJDBCMajorVersion() throws SQLException { return JDBC_MAJOR_VERSION; } @Override public int getJDBCMinorVersion() throws SQLException { return JDBC_MINOR_VERSION; } @Override public int getSQLStateType() throws SQLException { return sqlStateSQL; } @Override public boolean locatorsUpdateCopy() throws SQLException { return true; } @Override public boolean supportsStatementPooling() throws SQLException { return false; } @Override public RowIdLifetime getRowIdLifetime() throws SQLException { return RowIdLifetime.ROWID_UNSUPPORTED; } @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { String sql = "SELECT SCHEMA_NAME AS TABLE_SCHEM, CATALOG_NAME AS TABLE_CATALOG FROM INFORMATION_SCHEMA.SCHEMATA " + CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(CATALOG_NAME) like ? "; if (schemaPattern != null) sql = sql + "AND UPPER(SCHEMA_NAME) like ? "; sql = sql + "ORDER BY SCHEMA_NAME"; PreparedStatement statement = prepareStatement(sql, catalog, schemaPattern); return statement.executeQuery(); } @Override public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { return false; } @Override public boolean autoCommitFailureClosesAllResultSets() throws SQLException { return false; } @Override public ResultSet getClientInfoProperties() throws SQLException { String sql = "SELECT '' AS NAME, 0 AS MAX_LEN, '' AS DEFAULT_VALUE, '' AS DESCRIPTION " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS REMARKS, 0 AS FUNCTION_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, 1111 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, 0 AS NULLABLE, '' AS REMARKS, 0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = "select TABLE_CATALOG AS TABLE_CAT, TABLE_SCHEMA AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, " + "CASE " + " WHEN SPANNER_TYPE = 'ARRAY' THEN " + Types.ARRAY + " " + " WHEN SPANNER_TYPE = 'BOOL' THEN " + Types.BOOLEAN + " " + " WHEN SPANNER_TYPE = 'BYTES' THEN " + Types.BINARY + " " + " WHEN SPANNER_TYPE = 'DATE' THEN " + Types.DATE + " " + " WHEN SPANNER_TYPE = 'FLOAT64' THEN " + Types.DOUBLE + " " + " WHEN SPANNER_TYPE = 'INT64' THEN " + Types.BIGINT + " " + " WHEN SPANNER_TYPE = 'STRING' THEN " + Types.NVARCHAR + " " + " WHEN SPANNER_TYPE = 'STRUCT' THEN " + Types.STRUCT + " " + " WHEN SPANNER_TYPE = 'TIMESTAMP' THEN " + Types.TIMESTAMP + " " + "END AS DATA_TYPE, " + "0 AS COLUMN_SIZE, NULL AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 'USAGE_UNKNOWN' AS COLUMN_USAGE, NULL AS REMARKS, 0 AS CHAR_OCTET_LENGTH, IS_NULLABLE " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + getCatalogSchemaTableWhereClause("T", catalog, schemaPattern, tableNamePattern); if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public boolean generatedKeyAlwaysReturned() throws SQLException { return false; } }
package nl.topicus.jdbc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; import javax.sql.StatementEventListener; import com.google.rpc.Code; import nl.topicus.jdbc.exception.CloudSpannerSQLException; public class CloudSpannerPooledConnection implements PooledConnection, AutoCloseable { private final List<ConnectionEventListener> listeners = new LinkedList<>(); private Connection con; private ConnectionHandler last; private final boolean autoCommit; private final boolean isXA; /** * Creates a new PooledConnection representing the specified physical * connection. * * @param con * connection * @param autoCommit * whether to autocommit * @param isXA * whether connection is a XA connection */ public CloudSpannerPooledConnection(Connection con, boolean autoCommit, boolean isXA) { this.con = con; this.autoCommit = autoCommit; this.isXA = isXA; } public CloudSpannerPooledConnection(Connection con, boolean autoCommit) { this(con, autoCommit, false); } /** * Adds a listener for close or fatal error events on the connection handed * out to a client. */ @Override public void addConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.add(connectionEventListener); } /** * Removes a listener for close or fatal error events on the connection * handed out to a client. */ @Override public void removeConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.remove(connectionEventListener); } /** * Closes the physical database connection represented by this * PooledConnection. If any client has a connection based on this * PooledConnection, it is forcibly closed as well. */ @Override public void close() throws SQLException { if (last != null) { last.close(); if (!con.isClosed() && !con.getAutoCommit()) { try { con.rollback(); } catch (SQLException ignored) { // ignore } } } try { con.close(); } finally { con = null; } } /** * Gets a handle for a client to use. This is a wrapper around the physical * connection, so the client can call close and it will just return the * connection to the pool without really closing the physical connection. * * <p> * According to the JDBC 2.0 Optional Package spec (6.2.3), only one client * may have an active handle to the connection at a time, so if there is a * previous handle active when this is called, the previous one is forcibly * closed and its work rolled back. * </p> */ @Override public ICloudSpannerConnection getConnection() throws SQLException { if (con == null) { // Before throwing the exception, let's notify the registered // listeners about the error SQLException sqlException = new CloudSpannerSQLException("This PooledConnection has already been closed.", Code.FAILED_PRECONDITION); fireConnectionFatalError(sqlException); throw sqlException; } // If any error occurs while opening a new connection, the listeners // have to be notified. This gives a chance to connection pools to // eliminate bad pooled connections. try { // Only one connection can be open at a time from this // PooledConnection. See JDBC 2.0 Optional // Package spec section 6.2.3 if (last != null) { last.close(); if (!con.getAutoCommit()) { rollbackAndIgnoreException(); } con.clearWarnings(); } /* * In XA-mode, autocommit is handled in PGXAConnection, because it * depends on whether an XA-transaction is open or not */ if (!isXA) { con.setAutoCommit(autoCommit); } } catch (SQLException sqlException) { fireConnectionFatalError(sqlException); throw (SQLException) sqlException.fillInStackTrace(); } ConnectionHandler handler = new ConnectionHandler(con); last = handler; ICloudSpannerConnection proxyCon = (ICloudSpannerConnection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Connection.class, ICloudSpannerConnection.class }, handler); last.setProxy(proxyCon); return proxyCon; } private void rollbackAndIgnoreException() { try { con.rollback(); } catch (SQLException ignored) { // ignore exception } } /** * Used to fire a connection closed event to all listeners. */ void fireConnectionClosed() { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this // method call ConnectionEventListener[] local = listeners.toArray(new ConnectionEventListener[listeners.size()]); for (ConnectionEventListener listener : local) { if (evt == null) { evt = createConnectionEvent(null); } listener.connectionClosed(evt); } } /** * Used to fire a connection error event to all listeners. */ void fireConnectionFatalError(SQLException e) { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this // method call ConnectionEventListener[] local = listeners.toArray(new ConnectionEventListener[listeners.size()]); for (ConnectionEventListener listener : local) { if (evt == null) { evt = createConnectionEvent(e); } listener.connectionErrorOccurred(evt); } } protected ConnectionEvent createConnectionEvent(SQLException e) { return new ConnectionEvent(this, e); } private static final Set<Code> FATAL_CODES = new HashSet<>(); static { FATAL_CODES.add(Code.UNAUTHENTICATED); FATAL_CODES.add(Code.DATA_LOSS); FATAL_CODES.add(Code.INTERNAL); } private static boolean isFatalState(Code code) { if (code == null) { // no info, assume fatal return true; } return FATAL_CODES.contains(code); } /** * Fires a connection error event, but only if we think the exception is * fatal. * * @param e * the SQLException to consider */ private void fireConnectionError(SQLException e) { Code code = Code.UNKNOWN; if (e instanceof CloudSpannerSQLException) { code = ((CloudSpannerSQLException) e).getCode(); } if (!isFatalState(code)) { return; } fireConnectionFatalError(e); } /** * Instead of declaring a class implementing Connection, which would have to * be updated for every JDK rev, use a dynamic proxy to handle all calls * through the Connection interface. This is the part that requires JDK 1.3 * or higher, though JDK 1.2 could be supported with a 3rd-party proxy * package. */ private class ConnectionHandler implements InvocationHandler { private Connection con; private Connection proxy; // the Connection the client is currently // using, which is a proxy private boolean automatic = false; public ConnectionHandler(Connection con) { this.con = con; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); // From Object if (method.getDeclaringClass().equals(Object.class)) { return handleInvokeObjectMethod(method, args); } // All the rest is from the Connection or PGConnection interface if (methodName.equals("isClosed")) { return con == null || con.isClosed(); } if (methodName.equals("close")) { return handleInvokeClose(); } if (con == null || con.isClosed()) { throw new CloudSpannerSQLException(automatic ? "Connection has been closed automatically because a new connection was opened for the same PooledConnection or the PooledConnection has been closed." : "Connection has been closed.", Code.FAILED_PRECONDITION); } // From here on in, we invoke via reflection, catch exceptions, // and check if they're fatal before rethrowing. try { if (methodName.equals("createStatement")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Statement.class }, new StatementHandler(this, st)); } else if (methodName.equals("prepareCall")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { CallableStatement.class }, new StatementHandler(this, st)); } else if (methodName.equals("prepareStatement")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { PreparedStatement.class }, new StatementHandler(this, st)); } else { return method.invoke(con, args); } } catch (final InvocationTargetException ite) { final Throwable te = ite.getTargetException(); if (te instanceof SQLException) { fireConnectionError((SQLException) te); // Tell listeners // about exception // if it's fatal } throw te; } } private Object handleInvokeObjectMethod(Method method, Object[] args) throws Throwable { final String methodName = method.getName(); if (methodName.equals("toString")) { return "Pooled connection wrapping physical connection " + con; } if (methodName.equals("equals")) { return proxy == args[0]; } if (methodName.equals("hashCode")) { return System.identityHashCode(proxy); } try { return method.invoke(con, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } private Object handleInvokeClose() throws Throwable { // we are already closed and a double close // is not an error. if (con == null) { return null; } SQLException ex = null; if (!con.isClosed()) { if (!isXA && !con.getAutoCommit()) { try { con.rollback(); } catch (SQLException e) { ex = e; } } con.clearWarnings(); } con = null; this.proxy = null; last = null; fireConnectionClosed(); if (ex != null) { throw ex; } return null; } Connection getProxy() { return proxy; } void setProxy(Connection proxy) { this.proxy = proxy; } public void close() { if (con != null) { automatic = true; } con = null; proxy = null; // No close event fired here: see JDBC 2.0 Optional Package spec // section 6.3 } @SuppressWarnings("unused") public boolean isClosed() { return con == null; } } /** * Instead of declaring classes implementing Statement, PreparedStatement, * and CallableStatement, which would have to be updated for every JDK rev, * use a dynamic proxy to handle all calls through the Statement interfaces. * This is the part that requires JDK 1.3 or higher, though JDK 1.2 could be * supported with a 3rd-party proxy package. * * The StatementHandler is required in order to return the proper Connection * proxy for the getConnection method. */ private class StatementHandler implements InvocationHandler { private ConnectionHandler con; private Statement st; public StatementHandler(ConnectionHandler con, Statement st) { this.con = con; this.st = st; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); // From Object if (method.getDeclaringClass().equals(Object.class)) { return handleInvokeObjectMethod(proxy, method, args); } // All the rest is from the Statement interface if (methodName.equals("isClosed")) { return st == null || st.isClosed(); } if (methodName.equals("close")) { handleInvokeClose(); } if (st == null || st.isClosed()) { throw new CloudSpannerSQLException("Statement has been closed.", Code.FAILED_PRECONDITION); } if (methodName.equals("getConnection")) { return con.getProxy(); // the proxied connection, not a physical // connection } // Delegate the call to the proxied Statement. try { return method.invoke(st, args); } catch (final InvocationTargetException ite) { final Throwable te = ite.getTargetException(); if (te instanceof SQLException) { fireConnectionError((SQLException) te); // Tell listeners // about exception // if it's fatal } throw te; } } private Object handleInvokeObjectMethod(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); if (methodName.equals("toString")) { return "Pooled statement wrapping physical statement " + st; } if (methodName.equals("hashCode")) { return System.identityHashCode(proxy); } if (methodName.equals("equals")) { return proxy == args[0]; } return method.invoke(st, args); } private Object handleInvokeClose() throws Throwable { if (st == null || st.isClosed()) { return null; } con = null; final Statement oldSt = st; st = null; oldSt.close(); return null; } } /** * This implementation does nothing as the driver does not support pooled * statements. * * @see PooledConnection#removeStatementEventListener(StatementEventListener) */ @Override public void removeStatementEventListener(StatementEventListener listener) { // do nothing as pooled statements are not supported } /** * This implementation does nothing as the driver does not support pooled * statements. * * @see PooledConnection#removeStatementEventListener(StatementEventListener) */ @Override public void addStatementEventListener(StatementEventListener listener) { // do nothing as pooled statements are not supported } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("Method getParentLogger() is not supported"); } }
package nl.topicus.jdbc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; import javax.sql.StatementEventListener; import com.google.rpc.Code; import nl.topicus.jdbc.exception.CloudSpannerSQLException; public class CloudSpannerPooledConnection implements PooledConnection, AutoCloseable { private final List<ConnectionEventListener> listeners = new LinkedList<>(); private Connection con; private ConnectionHandler last; private final boolean autoCommit; private final boolean isXA; /** * Creates a new PooledConnection representing the specified physical * connection. * * @param con * connection * @param autoCommit * whether to autocommit * @param isXA * whether connection is a XA connection */ public CloudSpannerPooledConnection(Connection con, boolean autoCommit, boolean isXA) { this.con = con; this.autoCommit = autoCommit; this.isXA = isXA; } public CloudSpannerPooledConnection(Connection con, boolean autoCommit) { this(con, autoCommit, false); } /** * Adds a listener for close or fatal error events on the connection handed * out to a client. */ @Override public void addConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.add(connectionEventListener); } /** * Removes a listener for close or fatal error events on the connection * handed out to a client. */ @Override public void removeConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.remove(connectionEventListener); } /** * Closes the physical database connection represented by this * PooledConnection. If any client has a connection based on this * PooledConnection, it is forcibly closed as well. */ @Override public void close() throws SQLException { if (last != null) { last.close(); if (!con.isClosed() && !con.getAutoCommit()) { try { con.rollback(); } catch (SQLException ignored) { // ignore } } } try { con.close(); } finally { con = null; } } /** * Gets a handle for a client to use. This is a wrapper around the physical * connection, so the client can call close and it will just return the * connection to the pool without really closing the physical connection. * * <p> * According to the JDBC 2.0 Optional Package spec (6.2.3), only one client * may have an active handle to the connection at a time, so if there is a * previous handle active when this is called, the previous one is forcibly * closed and its work rolled back. * </p> */ @Override public ICloudSpannerConnection getConnection() throws SQLException { if (con == null) { // Before throwing the exception, let's notify the registered // listeners about the error SQLException sqlException = new CloudSpannerSQLException("This PooledConnection has already been closed.", Code.FAILED_PRECONDITION); fireConnectionFatalError(sqlException); throw sqlException; } // If any error occurs while opening a new connection, the listeners // have to be notified. This gives a chance to connection pools to // eliminate bad pooled connections. try { // Only one connection can be open at a time from this // PooledConnection. See JDBC 2.0 Optional // Package spec section 6.2.3 if (last != null) { last.close(); if (!con.getAutoCommit()) { rollbackAndIgnoreException(); } con.clearWarnings(); } /* * In XA-mode, autocommit is handled in PGXAConnection, because it * depends on whether an XA-transaction is open or not */ if (!isXA) { con.setAutoCommit(autoCommit); } } catch (SQLException sqlException) { fireConnectionFatalError(sqlException); throw (SQLException) sqlException.fillInStackTrace(); } ConnectionHandler handler = new ConnectionHandler(con); last = handler; ICloudSpannerConnection proxyCon = (ICloudSpannerConnection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Connection.class, ICloudSpannerConnection.class }, handler); last.setProxy(proxyCon); return proxyCon; } private void rollbackAndIgnoreException() { try { con.rollback(); } catch (SQLException ignored) { // ignore exception } } /** * Used to fire a connection closed event to all listeners. */ void fireConnectionClosed() { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this // method call ConnectionEventListener[] local = listeners.toArray(new ConnectionEventListener[listeners.size()]); for (ConnectionEventListener listener : local) { if (evt == null) { evt = createConnectionEvent(null); } listener.connectionClosed(evt); } } /** * Used to fire a connection error event to all listeners. */ void fireConnectionFatalError(SQLException e) { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this // method call ConnectionEventListener[] local = listeners.toArray(new ConnectionEventListener[listeners.size()]); for (ConnectionEventListener listener : local) { if (evt == null) { evt = createConnectionEvent(e); } listener.connectionErrorOccurred(evt); } } protected ConnectionEvent createConnectionEvent(SQLException e) { return new ConnectionEvent(this, e); } private static final Set<Code> FATAL_CODES = new HashSet<>(); static { FATAL_CODES.add(Code.UNAUTHENTICATED); FATAL_CODES.add(Code.DATA_LOSS); FATAL_CODES.add(Code.INTERNAL); } private static boolean isFatalState(Code code) { if (code == null) { // no info, assume fatal return true; } return FATAL_CODES.contains(code); } /** * Fires a connection error event, but only if we think the exception is * fatal. * * @param e * the SQLException to consider */ private void fireConnectionError(SQLException e) { Code code = Code.UNKNOWN; if (e instanceof CloudSpannerSQLException) { code = ((CloudSpannerSQLException) e).getCode(); } if (!isFatalState(code)) { return; } fireConnectionFatalError(e); } /** * Instead of declaring a class implementing Connection, which would have to * be updated for every JDK rev, use a dynamic proxy to handle all calls * through the Connection interface. This is the part that requires JDK 1.3 * or higher, though JDK 1.2 could be supported with a 3rd-party proxy * package. */ private class ConnectionHandler implements InvocationHandler { private Connection con; private Connection proxy; // the Connection the client is currently // using, which is a proxy private boolean automatic = false; public ConnectionHandler(Connection con) { this.con = con; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); // From Object if (method.getDeclaringClass().equals(Object.class)) { return handleInvokeObjectMethod(method, args); } // All the rest is from the Connection or PGConnection interface if (methodName.equals("isClosed")) { return con == null || con.isClosed(); } if (methodName.equals("close")) { return handleInvokeClose(); } if (con == null || con.isClosed()) { throw new CloudSpannerSQLException(automatic ? "Connection has been closed automatically because a new connection was opened for the same PooledConnection or the PooledConnection has been closed." : "Connection has been closed.", Code.FAILED_PRECONDITION); } // From here on in, we invoke via reflection, catch exceptions, // and check if they're fatal before rethrowing. try { if (methodName.equals("createStatement")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Statement.class }, new StatementHandler(this, st)); } else if (methodName.equals("prepareCall")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { CallableStatement.class }, new StatementHandler(this, st)); } else if (methodName.equals("prepareStatement")) { Statement st = (Statement) method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { PreparedStatement.class }, new StatementHandler(this, st)); } else { return method.invoke(con, args); } } catch (final InvocationTargetException ite) { final Throwable te = ite.getTargetException(); if (te instanceof SQLException) { fireConnectionError((SQLException) te); // Tell listeners // about exception // if it's fatal } throw te; } } private Object handleInvokeObjectMethod(Method method, Object[] args) throws Throwable { final String methodName = method.getName(); if (methodName.equals("toString")) { return "Pooled connection wrapping physical connection " + con; } if (methodName.equals("equals")) { return proxy == args[0]; } if (methodName.equals("hashCode")) { return System.identityHashCode(proxy); } try { return method.invoke(con, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } private Object handleInvokeClose() throws SQLException { // we are already closed and a double close // is not an error. if (con == null) { return null; } SQLException ex = null; if (!con.isClosed()) { if (!isXA && !con.getAutoCommit()) { try { con.rollback(); } catch (SQLException e) { ex = e; } } con.clearWarnings(); } con = null; this.proxy = null; last = null; fireConnectionClosed(); if (ex != null) { throw ex; } return null; } Connection getProxy() { return proxy; } void setProxy(Connection proxy) { this.proxy = proxy; } public void close() { if (con != null) { automatic = true; } con = null; proxy = null; // No close event fired here: see JDBC 2.0 Optional Package spec // section 6.3 } @SuppressWarnings("unused") public boolean isClosed() { return con == null; } } /** * Instead of declaring classes implementing Statement, PreparedStatement, * and CallableStatement, which would have to be updated for every JDK rev, * use a dynamic proxy to handle all calls through the Statement interfaces. * This is the part that requires JDK 1.3 or higher, though JDK 1.2 could be * supported with a 3rd-party proxy package. * * The StatementHandler is required in order to return the proper Connection * proxy for the getConnection method. */ private class StatementHandler implements InvocationHandler { private ConnectionHandler con; private Statement st; public StatementHandler(ConnectionHandler con, Statement st) { this.con = con; this.st = st; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); // From Object if (method.getDeclaringClass().equals(Object.class)) { return handleInvokeObjectMethod(proxy, method, args); } // All the rest is from the Statement interface if (methodName.equals("isClosed")) { return st == null || st.isClosed(); } if (methodName.equals("close")) { return handleInvokeClose(); } if (st == null || st.isClosed()) { throw new CloudSpannerSQLException("Statement has been closed.", Code.FAILED_PRECONDITION); } if (methodName.equals("getConnection")) { return con.getProxy(); // the proxied connection, not a physical // connection } // Delegate the call to the proxied Statement. try { return method.invoke(st, args); } catch (final InvocationTargetException ite) { final Throwable te = ite.getTargetException(); if (te instanceof SQLException) { fireConnectionError((SQLException) te); // Tell listeners // about exception // if it's fatal } throw te; } } private Object handleInvokeObjectMethod(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String methodName = method.getName(); if (methodName.equals("toString")) { return "Pooled statement wrapping physical statement " + st; } if (methodName.equals("hashCode")) { return System.identityHashCode(proxy); } if (methodName.equals("equals")) { return proxy == args[0]; } return method.invoke(st, args); } private Object handleInvokeClose() throws SQLException { if (st == null || st.isClosed()) { return null; } con = null; final Statement oldSt = st; st = null; oldSt.close(); return null; } } /** * This implementation does nothing as the driver does not support pooled * statements. * * @see PooledConnection#removeStatementEventListener(StatementEventListener) */ @Override public void removeStatementEventListener(StatementEventListener listener) { // do nothing as pooled statements are not supported } /** * This implementation does nothing as the driver does not support pooled * statements. * * @see PooledConnection#removeStatementEventListener(StatementEventListener) */ @Override public void addStatementEventListener(StatementEventListener listener) { // do nothing as pooled statements are not supported } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("Method getParentLogger() is not supported"); } }
package omtteam.omlib.compatability; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.event.FMLInterModComms; import omtteam.omlib.OMLib; import omtteam.omlib.reference.Reference; @SuppressWarnings("WeakerAccess") public class ModCompatibility { public static boolean IC2Loaded = false; public static boolean TeslaLoaded = false; public static boolean CoFHApiLoaded = false; public static boolean OpenComputersLoaded = false; public static boolean ComputerCraftLoaded = false; public static final String IC2ModId = "IC2"; public static final String TeslaModId = "tesla"; public static final String CoFHApiModId = "CoFHAPI"; public static final String OCModID = "OpenComputers"; public static final String CCModID = "ComputerCraft"; public static void checkForMods() { IC2Loaded = Loader.isModLoaded(IC2ModId); TeslaLoaded = Loader.isModLoaded(TeslaModId); OpenComputersLoaded = Loader.isModLoaded(OCModID); ComputerCraftLoaded = Loader.isModLoaded(CCModID); fixIC2Loading(); printDetectedMods(); } private static void printDetectedMods() { String foundMods = "Found the following mods: "; foundMods += IC2Loaded ? "IC2 " : ""; foundMods += TeslaLoaded ? "Tesla " : ""; foundMods += CoFHApiLoaded ? "CoFHApi " : ""; foundMods += OpenComputersLoaded ? "OpenComputers " : ""; OMLib.getLogger().info(foundMods); } public static void fixIC2Loading() { /* if (IC2Loaded) { try { Class.forName("ic2.api.energy.tile.IEnergySink", false, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { IC2Loaded = false; Logger.getLogger("OMlib").severe("IC2 should be present but class not found!"); } } */ } private static void addVersionCheckerInfo() { NBTTagCompound versionchecker = new NBTTagCompound(); versionchecker.setString("curseProjectName", "omlib"); versionchecker.setString("curseFilenameParser", "OMLib-1.10.2-[].jar"); versionchecker.setString("modDisplayName", "OMLib"); versionchecker.setString("oldVersion", Reference.VERSION); FMLInterModComms.sendRuntimeMessage("omlib", "VersionChecker", "addCurseCheck", versionchecker); } public static void performModCompat() { addVersionCheckerInfo(); } }
package org.animotron.graph.builder; import org.animotron.exception.AnimoException; import org.animotron.graph.index.Cache; import org.animotron.statement.Statement; import org.animotron.statement.operator.THE; import org.animotron.utils.MessageDigester; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import java.io.IOException; import java.security.MessageDigest; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static org.animotron.graph.AnimoGraph.*; import static org.animotron.graph.Properties.*; import static org.animotron.graph.RelationshipTypes.REV; import static org.animotron.utils.MessageDigester.cloneMD; import static org.animotron.utils.MessageDigester.updateMD; /** * Animo graph builder, it do optimization/compression and * inform listeners on store/delete events. * * Direct graph as input from top element to bottom processing strategy. * * Methods to use: * * startGraph() * endGraph() * * start(VALUE prefix, VALUE ns, VALUE reference, VALUE value) * start(Statement statement, VALUE prefix, VALUE ns, VALUE reference, VALUE value) * end() * * relationship() * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class FastGraphBuilder extends GraphBuilder { private List<Object[]> flow; private Relationship relationship; private Node root; private byte[] hash; public FastGraphBuilder () { super(); } public FastGraphBuilder (boolean ignoreNotFound) { super(ignoreNotFound); } @Override protected void fail(Throwable e) { if (root != null) { destructive(root); } } @Override public Relationship relationship() { return relationship; } @Override public void startGraph() { flow = new LinkedList<Object[]>(); root = null; } @Override public void endGraph() throws AnimoException, IOException { Iterator<Object[]> it = flow.iterator(); if (it.hasNext()) { Object[] o = it.next(); Statement statement = (Statement) o[1]; relationship = Cache.RELATIONSHIP.get(hash); if (relationship == null) { Object reference = statement instanceof THE && o[2] == null ? MessageDigester.byteArrayToHex(hash) : o[2]; root = createNode(); o[6] = Cache.NODE.get(hash) != null; Relationship r = statement.build(root, reference, hash, true, ignoreNotFound); Node end = r.getEndNode(); o[3] = r; o[4] = end; step(); while (it.hasNext()) { build(it.next()); step(); } if (statement instanceof THE) { relationship = THE._.get(reference); if (relationship == null) { relationship = getROOT().createRelationshipTo(end, THE._); MODIFIED.set(relationship, System.currentTimeMillis()); UUID.set(relationship, java.util.UUID.randomUUID().toString()); HASH.set(relationship, hash); ARID.set(relationship, relationship.getId()); ARID.set(end, end.getId()); THE._.add(relationship, reference); Cache.RELATIONSHIP.add(relationship, hash); } else { Node n = relationship.getEndNode(); long arid = (Long) ARID.get(n); Node rn = getDb().getNodeById(arid); Relationship rr = rn.createRelationshipTo(end, REV); MODIFIED.set(rr, System.currentTimeMillis()); UUID.set(rr, java.util.UUID.randomUUID().toString()); HASH.set(rr, hash); ARID.set(relationship, rr.getId()); ARID.set(n, end.getId()); } preparative(relationship); } else { relationship = getROOT().createRelationshipTo(end, r.getType()); Cache.RELATIONSHIP.add(relationship, hash); MODIFIED.set(relationship, System.currentTimeMillis()); HASH.set(relationship, hash); } r.delete(); root.delete(); } else if (statement instanceof THE) { // Node n = relationship.getEndNode(); // long arid = (Long) ARID.get(n); // Node rn = getDb().getNodeById(arid); // Relationship rr = n.createRelationshipTo(end, REV); // MODIFIED.set(rr, System.currentTimeMillis()); // UUID.set(rr, java.util.UUID.randomUUID().toString()); // HASH.set(rr, hash); // ARID.set(relationship, rr.getId()); // ARID.set(n, end.getId()); } } } @Override protected Object[] start(Statement statement, Object reference, boolean hasChild) throws AnimoException { Object[] parent = hasParent() ? peekParent() : null; MessageDigest md = MessageDigester.md(); byte[] hash = null; boolean ready = !hasChild && reference != null; if (ready) { updateMD(md, reference); hash = cloneMD(md).digest(); updateMD(md, statement); } else if (reference != null) { updateMD(md, reference); } Object[] o = { md, // 0 message digest statement, // 1 statement reference, // 2 name or value null, // 3 current relationship null, // 4 current node parent, // 5 parent item false, // 6 is done? ready, // 7 is ready? hash // 8 hash }; flow.add(o); return o; } @Override protected byte[] end(Object[] o, boolean hasChild) { MessageDigest md = (MessageDigest) o[0]; if (!(Boolean) o[7]) { updateMD(md, (Statement) o[1]); } o[8] = hash = md.digest(); return hash; } @Override public void bind(Relationship r, Object[] p, byte[] hash) throws IOException { step(); Object[] o = {p, r}; flow.add(o); } private void build(Object[] item) throws AnimoException { Relationship r; if (item.length == 2) { Node n = (Node) ((Object[]) item[0])[4]; r = copy(n, (Relationship) item[1]); CONTEXT.set(n, true); } else { Object[] p = (Object[]) item[5]; if (p != null) { if ((Boolean) p[6]) { item[6] = true; return; } } Statement statement = (Statement) item[1]; Object reference = item[2]; byte[] hash = (byte[]) item[8]; Node parent = (Node) p[4]; item[6] = Cache.NODE.get(hash) != null; r = statement.build(parent, reference, hash, true, ignoreNotFound); item[3] = r; item[4] = r.getEndNode(); } order(r); } }
package org.sana.android.task; import org.sana.android.util.SanaUtil; import android.app.ProgressDialog; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; /** * Task for resetting the application database. * * @author Sana Development Team * */ public class ResetDatabaseTask extends AsyncTask<Context, Void, Integer> { private static final String TAG = ResetDatabaseTask.class.getSimpleName(); private ProgressDialog progressDialog; private Context mContext = null; // TODO context leak? private boolean quiet = false; private Uri[] uris = new Uri[0]; /** * A new task for resetting the database. * @param c the current Context. */ public ResetDatabaseTask(Context c) { this.mContext = c; } /** * A new task for resetting the database. * @param c the current Context. */ public ResetDatabaseTask(Context c, boolean quiet) { this.mContext = c; this.quiet = quiet; } /** * A new task for resetting the database. * @param c the current Context. */ public ResetDatabaseTask(Context c, boolean quiet, Uri[] uris) { this.mContext = c; this.quiet = quiet; this.uris = new Uri[uris.length]; int index = 0; for(Uri uri:uris){ this.uris[index] = uri; index++; } } /** {@inheritDoc} */ @Override protected Integer doInBackground(Context... params) { Log.i(TAG, "Executing ResetDatabaseTask"); Context c = params[0]; try{ SanaUtil.clearDatabase(c); for(Uri uri:uris){ Log.d(TAG, "Clearing: " + uri); c.getContentResolver().delete(uri, null, null); } SanaUtil.loadDefaultDatabase(c); } catch(Exception e){ Log.e(TAG, "Could not sync. " + e.toString()); } return 0; } /** {@inheritDoc} */ @Override protected void onPreExecute() { Log.i(TAG, "About to execute ResetDatabaseTask"); if(quiet) return; if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } progressDialog = new ProgressDialog(mContext); progressDialog.setMessage("Clearing Database"); // TODO i18n progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.show(); } /** {@inheritDoc} */ @Override protected void onPostExecute(Integer result) { Log.i(TAG, "Completed ResetDatabaseTask"); if(quiet) return; if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } }
package org.bouncycastle.crypto.modes; import java.io.ByteArrayOutputStream; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.macs.CBCBlockCipherMac; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; /** * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in * NIST Special Publication 800-38C. * <p> * <b>Note</b>: this mode is a packet mode - it needs all the data up front. */ public class CCMBlockCipher implements AEADBlockCipher { private BlockCipher cipher; private int blockSize; private boolean forEncryption; private byte[] nonce; private byte[] initialAssociatedText; private int macSize; private CipherParameters keyParam; private byte[] macBlock; private ByteArrayOutputStream associatedText = new ByteArrayOutputStream(); private ByteArrayOutputStream data = new ByteArrayOutputStream(); /** * Basic constructor. * * @param c the block cipher to be used. */ public CCMBlockCipher(BlockCipher c) { this.cipher = c; this.blockSize = c.getBlockSize(); this.macBlock = new byte[blockSize]; if (blockSize != 16) { throw new IllegalArgumentException("cipher required with a block size of 16."); } } /** * return the underlying block cipher that we are wrapping. * * @return the underlying block cipher that we are wrapping. */ public BlockCipher getUnderlyingCipher() { return cipher; } public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { this.forEncryption = forEncryption; if (params instanceof AEADParameters) { AEADParameters param = (AEADParameters)params; nonce = param.getNonce(); initialAssociatedText = param.getAssociatedText(); macSize = param.getMacSize() / 8; keyParam = param.getKey(); } else if (params instanceof ParametersWithIV) { ParametersWithIV param = (ParametersWithIV)params; nonce = param.getIV(); initialAssociatedText = null; macSize = macBlock.length / 2; keyParam = param.getParameters(); } else { throw new IllegalArgumentException("invalid parameters passed to CCM"); } if (nonce == null || nonce.length < 7 || nonce.length > 13) { throw new IllegalArgumentException("nonce must have length from 7 to 13 octets"); } } public String getAlgorithmName() { return cipher.getAlgorithmName() + "/CCM"; } public void processAADByte(byte in) { associatedText.write(in); } public void processAADBytes(byte[] in, int inOff, int len) { // TODO: Process AAD online associatedText.write(in, inOff, len); } public int processByte(byte in, byte[] out, int outOff) throws DataLengthException, IllegalStateException { data.write(in); return 0; } public int processBytes(byte[] in, int inOff, int inLen, byte[] out, int outOff) throws DataLengthException, IllegalStateException { data.write(in, inOff, inLen); return 0; } public int doFinal(byte[] out, int outOff) throws IllegalStateException, InvalidCipherTextException { byte[] text = data.toByteArray(); byte[] enc = processPacket(text, 0, text.length); System.arraycopy(enc, 0, out, outOff, enc.length); reset(); return enc.length; } public void reset() { cipher.reset(); associatedText.reset(); data.reset(); } /** * Returns a byte array containing the mac calculated as part of the * last encrypt or decrypt operation. * * @return the last mac calculated. */ public byte[] getMac() { byte[] mac = new byte[macSize]; System.arraycopy(macBlock, 0, mac, 0, mac.length); return mac; } public int getUpdateOutputSize(int len) { return 0; } public int getOutputSize(int len) { int totalData = len + data.size(); if (forEncryption) { return totalData + macSize; } return totalData < macSize ? 0 : totalData - macSize; } public byte[] processPacket(byte[] in, int inOff, int inLen) throws IllegalStateException, InvalidCipherTextException { // TODO: handle null keyParam (e.g. via RepeatedKeySpec) // Need to keep the CTR and CBC Mac parts around and reset if (keyParam == null) { throw new IllegalStateException("CCM cipher unitialized."); } int n = nonce.length; int q = 15 - n; if (q < 4) { int limitLen = 1 << (8 * q); if (inLen >= limitLen) { throw new IllegalStateException("CCM packet too large for choice of q."); } } byte[] iv = new byte[blockSize]; iv[0] = (byte)((q - 1) & 0x7); System.arraycopy(nonce, 0, iv, 1, nonce.length); BlockCipher ctrCipher = new SICBlockCipher(cipher); ctrCipher.init(forEncryption, new ParametersWithIV(keyParam, iv)); int index = inOff; int outOff = 0; byte[] output; if (forEncryption) { output = new byte[inLen + macSize]; calculateMac(in, inOff, inLen, macBlock); ctrCipher.processBlock(macBlock, 0, macBlock, 0); while (index < inLen - blockSize) { ctrCipher.processBlock(in, index, output, outOff); outOff += blockSize; index += blockSize; } byte[] block = new byte[blockSize]; System.arraycopy(in, index, block, 0, inLen - index); ctrCipher.processBlock(block, 0, block, 0); System.arraycopy(block, 0, output, outOff, inLen - index); outOff += inLen - index; System.arraycopy(macBlock, 0, output, outOff, output.length - outOff); } else { output = new byte[inLen - macSize]; System.arraycopy(in, inOff + inLen - macSize, macBlock, 0, macSize); ctrCipher.processBlock(macBlock, 0, macBlock, 0); for (int i = macSize; i != macBlock.length; i++) { macBlock[i] = 0; } while (outOff < output.length - blockSize) { ctrCipher.processBlock(in, index, output, outOff); outOff += blockSize; index += blockSize; } byte[] block = new byte[blockSize]; System.arraycopy(in, index, block, 0, output.length - outOff); ctrCipher.processBlock(block, 0, block, 0); System.arraycopy(block, 0, output, outOff, output.length - outOff); byte[] calculatedMacBlock = new byte[blockSize]; calculateMac(output, 0, output.length, calculatedMacBlock); if (!Arrays.constantTimeAreEqual(macBlock, calculatedMacBlock)) { throw new InvalidCipherTextException("mac check in CCM failed"); } } return output; } private int calculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) { Mac cMac = new CBCBlockCipherMac(cipher, macSize * 8); cMac.init(keyParam); // build b0 byte[] b0 = new byte[16]; if (hasAssociatedText()) { b0[0] |= 0x40; } b0[0] |= (((cMac.getMacSize() - 2) / 2) & 0x7) << 3; b0[0] |= ((15 - nonce.length) - 1) & 0x7; System.arraycopy(nonce, 0, b0, 1, nonce.length); int q = dataLen; int count = 1; while (q > 0) { b0[b0.length - count] = (byte)(q & 0xff); q >>>= 8; count++; } cMac.update(b0, 0, b0.length); // process associated text if (hasAssociatedText()) { int extra; int textLength = getAssociatedTextLength(); if (textLength < ((1 << 16) - (1 << 8))) { cMac.update((byte)(textLength >> 8)); cMac.update((byte)textLength); extra = 2; } else // can't go any higher than 2^32 { cMac.update((byte)0xff); cMac.update((byte)0xfe); cMac.update((byte)(textLength >> 24)); cMac.update((byte)(textLength >> 16)); cMac.update((byte)(textLength >> 8)); cMac.update((byte)textLength); extra = 6; } if (initialAssociatedText != null) { cMac.update(initialAssociatedText, 0, initialAssociatedText.length); } if (associatedText.size() > 0) { byte[] tmp = associatedText.toByteArray(); cMac.update(tmp, 0, tmp.length); } extra = (extra + textLength) % 16; if (extra != 0) { for (int i = extra; i != 16; i++) { cMac.update((byte)0x00); } } } // add the text cMac.update(data, dataOff, dataLen); return cMac.doFinal(macBlock, 0); } private int getAssociatedTextLength() { return associatedText.size() + ((initialAssociatedText == null) ? 0 : initialAssociatedText.length); } private boolean hasAssociatedText() { return getAssociatedTextLength() > 0; } }
package org.ccci.gto.android.common.util; import android.text.TextUtils; public final class StringUtils { private StringUtils() { } @Deprecated public static String join(final String sep, final String... parts) { return TextUtils.join(sep, parts); } }
package org.cdc.gov.sdp.queue; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Map; import javax.sql.DataSource; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; /** * Component for handing messages within a defined database structure. The table * name and datasource to use are provided as parameters. Currently, the * remaining portion of the URI, after the component prefix, is not used. * * @author Betsy Cole */ public class DatabaseQueueComponent extends UriEndpointComponent { public DatabaseQueueComponent() { super(DatabaseQueueEndpoint.class); } public DatabaseQueueComponent(Class<? extends Endpoint> endpointClass) { super(endpointClass); } public DatabaseQueueComponent(CamelContext context) { super(context, DatabaseQueueEndpoint.class); } public DatabaseQueueComponent(CamelContext context, Class<? extends Endpoint> endpointClass) { super(context, endpointClass); } public String getCreateCommand(String tableName) { return ("CREATE TABLE IF NOT EXISTS " + tableName + " (id bigserial primary key," + "cbr_id varchar(255) NOT NULL, source varchar(255) NOT NULL, source_id varchar(255) NOT NULL," + "source_attributes text default NULL, batch boolean default false, batch_index int default 0," + "payload text NOT NULL, cbr_recevied_time varchar (255) NOT NULL, cbr_delivered_time varchar (255) default NULL," + "sender varchar (255) default NULL, recipient varchar (255) default NULL, errorCode varchar (255) default NULL," + "errorMessage varchar (255) default NULL, attempts int default 0, status varchar (255) default 'queued'," + "created_at varchar (255) default NULL, updated_at varchar (255) default NULL)"); } public void createIfNotExists(DataSource ds, String tableName) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = ds.getConnection(); ps = conn.prepareStatement(getCreateCommand(tableName)); ps.executeUpdate(); } finally { ps.close(); conn.close(); } } @Override protected Endpoint createEndpoint(String uri, String tableName, Map<String, Object> parameters) throws Exception { DataSource ds = resolveAndRemoveReferenceParameter(parameters, "dataSource", DataSource.class); if (ds == null) { throw new IllegalArgumentException("DataSource must be configured"); } this.createIfNotExists(ds, tableName); DatabaseQueueEndpoint endpoint = new DatabaseQueueEndpoint(uri, this, ds, tableName); return endpoint; } }
package org.foo; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import org.apache.chemistry.opencmis.commons.data.ContentStream; import org.apache.chemistry.opencmis.commons.data.ExtensionsData; import org.apache.chemistry.opencmis.commons.data.MutableContentStream; import org.apache.chemistry.opencmis.commons.server.CallContext; import org.apache.chemistry.opencmis.commons.server.CmisService; import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStream; import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory; import org.apache.chemistry.opencmis.server.support.wrapper.AbstractCmisServiceWrapper; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap; import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Example of a minimal Cmis Custom Service Wrapper (logging example) * * Add the following ** to the repo.properties to have framework hook into chain * The number at the key is the position in the wrapper stack. Lower numbers are * outer wrappers, higher numbers are inner wrappers. * * ** add the following line to your repo.properties file in your servers war * servicewrapper.1=org.apache.chemistry.opencmis.server.support.CmisCustomLoggingServiceWrapper * * See the frameworks SimpleLoggingCmisServiceWrapper for a more generic and * complete example * */ public class CmisCustomPdfWatermarkServiceWrapper extends AbstractCmisServiceWrapper { // slf4j example private static final Logger LOG = LoggerFactory.getLogger(CmisCustomPdfWatermarkServiceWrapper.class); // provide constructor public CmisCustomPdfWatermarkServiceWrapper(CmisService service) { super(service); } /** * Initializes the wrapper with a set of optional parameters from the properties file */ @Override public void initialize(Object[] params) { // TBD - add paragraph explaining how this gets called once for each extension // giving the extension an opportunity to cache any of its optional parameters. LOG.info("Initializing the CmisCustomPdfWatermarkServiceWrapper."); // store the filter value here } /** * slf logging version with dual output to console and slf */ protected void slflog(String operation, String repositoryId) { if (repositoryId == null) { repositoryId = "<none>"; } HttpServletRequest request = (HttpServletRequest) getCallContext().get(CallContext.HTTP_SERVLET_REQUEST); String userAgent = request.getHeader("User-Agent"); if (userAgent == null) { userAgent = "<unknown>"; } String binding = getCallContext().getBinding(); LOG.info("Operation: {}, Repository ID: {}, Binding: {}, User Agent: {}", operation, repositoryId, binding, userAgent); // also dump to console for testing String result = String.format("Operation: %s, Repository ID: %s, Binding: %s, User Agent: %s", operation, repositoryId, binding, userAgent); System.out.println(result); } @Override public ContentStream getContentStream(String repositoryId, String objectId, String streamId, BigInteger offset, BigInteger length, ExtensionsData extension) { slflog("getContentStream override from Chameleon module long startTime = System.currentTimeMillis(); CallContext sharedContext = this.getCallContext(); // Get the native domain object from the call context if one is shared by the vendor (example only) // Your CMIS vendor's documentation must expose the name of any shared objects they place here for extensions. // Object objShared = sharedContext.get("shared_key_name_from_vendor"); MutableContentStream retVal = (MutableContentStream)getWrappedService().getContentStream(repositoryId, objectId, streamId, offset, length, extension); if ((retVal != null) && (retVal.getMimeType().contains("pdf"))) { InputStream rawStream = retVal.getStream(); // return a pdfbox document object // for debugging only - load to pdfbox and stream out //PDDocument modifiedPDF = watermarkPDF_loadOnly(rawStream); // actual watermark code PDDocument modifiedPDF = watermarkPDF(rawStream); // Extra credit here. Replace with ThresholdOutputStream or find another // way to handle very large objects in a small memory footprint. //ByteArrayOutputStream out = new ByteArrayOutputStream(); ThresholdOutputStream out = ((ThresholdOutputStreamFactory) sharedContext.get(CallContext.STREAM_FACTORY)).newOutputStream(); try { modifiedPDF.save(out); modifiedPDF.close(); InputStream modifiedInputStream = out.getInputStream(); //new ByteArrayInputStream(out.toByteArray()); // now write the stream back to the ContentStream object retVal.setStream(modifiedInputStream); } catch (Exception e) { slflog("error transposing stream getContentStream ", e.getMessage()); try { // since there was an error restore the original stream without the watermark retVal.getStream().reset(); } catch (IOException e1) { e1.printStackTrace(); // serious problem } } } // if pdf stream // dual log output in case logger not configured LOG.info("[CmisCustomServiceWrapper] Exiting method getContentStream. time (ms):" + (System.currentTimeMillis() - startTime)); System.out.println("[CmisCustomServiceWrapper] Exiting method getContentStream. time (ms):" + (System.currentTimeMillis() - startTime)); return retVal; } public PDDocument watermarkPDF(InputStream rawStream) { PDDocument pdf = null; try { pdf = PDDocument.load(rawStream); // Load watermark from classes directory cmis.jpg // Alternatives: // 1. Use a pdf document from the repository (via a fixed path) so the // watermark can be changed at runtime by an administrator. // 2. Dynamically generate a watermark based on the username / time // date and users ip address. InputStream watermarkStream = CmisCustomPdfWatermarkServiceWrapper.class.getClassLoader().getResourceAsStream("cmis.png"); BufferedImage buffered = ImageIO.read(watermarkStream); // Exercise A - add image to all pages of document. // Loop through pages in PDF //List pages = pdf.getDocumentCatalog().getAllPages(); //System.out.println("pdf loaded from stream. Pages found:" + pages.size()); //Iterator iter = pages.iterator(); // while(iter.hasNext()) // PDPage page = (PDPage)iter.next(); addImageToPage(pdf, 0, 0, 0, 1.0f, buffered); } catch (Exception e) { slflog("error watermarking pdf in getContentStream ", e.getMessage()); } return pdf; } // Original code taken from Nick Russler's example here: // and modified to use a BufferedImage directly. // Thank's Nick. public void addImageToPage(PDDocument document, int pdfpage, int x, int y, float scale, BufferedImage tmp_image) throws IOException { // Convert the image to TYPE_4BYTE_ABGR so PDFBox won't throw exceptions (e.g. for transparent png's). BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); image.createGraphics().drawRenderedImage(tmp_image, null); PDXObjectImage ximage = new PDPixelMap(document, image); PDPage page = (PDPage)document.getDocumentCatalog().getAllPages().get(pdfpage); PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true); contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale); contentStream.close(); } /** * Code just for showing an example of the findbugs output */ private void FindBugsExampleError() { // As a findbugs example String str1 = ""; Integer i = 1; if (str1 == i.toString()) { System.out.println("Bad code. Findbugs example"); } // end of findbugs example } }
package org.gavelproject.sanction; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import gavel.api.sanction.SanctionCategory; import gavel.api.sanction.SanctionCategoryBuilder; import gavel.impl.common.Enums; /** * Static utility methods pertaining to {@link SanctionCategory} instances. * * @author igorcadelima * */ public final class SanctionCategories { static final String NAME = "category"; private SanctionCategories() {} /** * Return a new {@link SanctionCategoryImpl} object initialised to the value represented by the * specified {@code Element}. * * @param el element to be parsed * @return {@link SanctionCategoryImpl} object represented by {@code el} * @throws NullPointerException if element is {@code null} */ public static SanctionCategory of(Element el) { NodeList dimensions = el.getChildNodes(); SanctionCategoryBuilder builder = builder(); for (int i = 0; i < dimensions.getLength(); i++) { Node dimensionNode = dimensions.item(i); String dimension = dimensionNode.getTextContent(); switch (dimensionNode.getNodeName()) { case "purpose": builder.purpose(Enums.lookup(SanctionPurposeImpl.class, dimension)); break; case "issuer": builder.issuer(Enums.lookup(SanctionIssuerImpl.class, dimension)); break; case "locus": builder.locus(Enums.lookup(SanctionLocusImpl.class, dimension)); break; case "mode": builder.mode(Enums.lookup(SanctionModeImpl.class, dimension)); break; case "polarity": builder.polarity(Enums.lookup(SanctionPolarityImpl.class, dimension)); break; case "discernability": builder.discernability(Enums.lookup(SanctionDiscernabilityImpl.class, dimension)); break; } } return builder.build(); } public static SanctionCategory tryParse(String in) { Pattern pattern = Pattern.compile("sanction_category\\\\s*(" + "\\s*purpose\\s*\\(\\s*(\\w+)\\s*\\)," + "\\s*issuer\\s*\\(\\s*(\\w+)\\s*\\)," + "\\s*locus\\s*\\(\\s*(\\w+)\\s*\\)," + "\\s*mode\\s*\\(\\s*(\\w+)\\s*\\)," + "\\s*polarity\\s*\\(\\s*(\\w+)\\s*\\)," + "\\s*discernability\\s*\\(\\s*(\\w+)\\s*\\)\\)"); Matcher matcher = pattern.matcher(in); matcher.find(); if (matcher.matches()) { return builder().purpose(Enums.lookup(SanctionPurposeImpl.class, matcher.group(1))) .issuer(Enums.lookup(SanctionIssuerImpl.class, matcher.group(2))) .locus(Enums.lookup(SanctionLocusImpl.class, matcher.group(3))) .mode(Enums.lookup(SanctionModeImpl.class, matcher.group(4))) .polarity(Enums.lookup(SanctionPolarityImpl.class, matcher.group(5))) .discernability( Enums.lookup(SanctionDiscernabilityImpl.class, matcher.group(6))) .build(); } return null; } /** Return a builder for {@link SanctionCategory}. */ public static SanctionCategoryBuilder builder() { return new SanctionCategoryImpl.Builder(); } }
package org.grobid.core.utilities; import com.google.common.collect.Iterables; import net.sf.saxon.lib.Logger; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.grobid.core.data.Measurement; import org.grobid.core.data.Quantity; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.layout.LayoutToken; import java.util.*; import java.util.stream.Collectors; import static org.apache.commons.collections4.CollectionUtils.isEmpty; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.length; public class QuantityOperations { public static List<Quantity> toQuantityList(Measurement m) { List<Quantity> quantitiesList = new LinkedList<>(); if (UnitUtilities.Measurement_Type.VALUE.equals(m.getType())) { quantitiesList.add(m.getQuantityAtomic()); } else if (UnitUtilities.Measurement_Type.INTERVAL_MIN_MAX.equals(m.getType())) { CollectionUtils.addIgnoreNull(quantitiesList, m.getQuantityLeast()); CollectionUtils.addIgnoreNull(quantitiesList, m.getQuantityMost()); } else if (UnitUtilities.Measurement_Type.INTERVAL_BASE_RANGE.equals(m.getType())) { CollectionUtils.addIgnoreNull(quantitiesList, m.getQuantityBase()); CollectionUtils.addIgnoreNull(quantitiesList, m.getQuantityRange()); } else if (UnitUtilities.Measurement_Type.CONJUNCTION.equals(m.getType())) { quantitiesList.addAll(m.getQuantityList()); } return quantitiesList; } public static List<OffsetPosition> getOffset(Measurement measurement) { return toQuantityList(measurement) .stream() .flatMap(q -> getOffsets(q).stream()) .sorted(Comparator.comparing(o -> o.end)) .collect(Collectors.toList()); } /** * transform a list measurement into a list of measurement ordered by the lower offset */ public static List<OffsetPosition> getOffset(List<Measurement> measurements) { return measurements .stream() .flatMap(m -> toQuantityList(m).stream().flatMap(q -> getOffsets(q).stream())) .sorted(Comparator.comparing(o -> o.end)) .distinct() .collect(Collectors.toList()); } /** * Return the list of all offsets in a quantity, from rawValue and rawUnit (if present). */ public static List<OffsetPosition> getOffsets(Quantity quantity) { List<OffsetPosition> offsets = new ArrayList<>(); if (quantity == null) { return offsets; } offsets.add(new OffsetPosition(quantity.getOffsetStart(), quantity.getOffsetEnd())); if (quantity.getRawUnit() != null) { offsets.add(new OffsetPosition(quantity.getRawUnit().getOffsetStart(), quantity.getRawUnit().getOffsetEnd())); } return offsets.stream() .sorted(Comparator.comparing(o -> o.end)) .collect(Collectors.toList()); } public static List<OffsetPosition> getOffsets(List<Quantity> quantities) { List<OffsetPosition> offsets = new ArrayList<>(); if (isEmpty(quantities)) { return offsets; } offsets = quantities.stream().flatMap(q -> { List<OffsetPosition> output = getOffsets(q); return output.stream(); }).collect(Collectors.toList()); return offsets.stream() .sorted(Comparator.comparing(o -> o.start)) .collect(Collectors.toList()); } /** * Given a list of offsets returns the boundaries these offsets cover */ public static OffsetPosition getContainingOffset(List<OffsetPosition> offsetList) { List<OffsetPosition> sorted = offsetList .stream() .sorted(Comparator.comparing(o -> o.end)) .collect(Collectors.toList()); return new OffsetPosition(sorted.get(0).start, Iterables.getLast(sorted).end); } /** * Given a quantity compute the offsets */ public static OffsetPosition getContainingOffset(Quantity quantity) { return getContainingOffset(getOffsets(quantity)); } /** * This method takes in input a list of tokens and a list of offsets representing special entities and * * @return a list of booleans of the same size of the initial layout token, flagging all the * tokens within the offsets */ public static List<Boolean> synchroniseLayoutTokensWithOffsets(List<LayoutToken> tokens, List<OffsetPosition> offsets) { List<Boolean> isMeasure = new ArrayList<>(); if (CollectionUtils.isEmpty(offsets)) { tokens.stream().forEach(t -> isMeasure.add(Boolean.FALSE)); return isMeasure; } int globalOffset = 0; if (isNotEmpty(tokens)) { globalOffset = tokens.get(0).getOffset(); } int mentionId = 0; OffsetPosition offset = offsets.get(mentionId); for (LayoutToken token : tokens) { //normalise the offsets int mentionStart = globalOffset + offset.start; int mentionEnd = globalOffset + offset.end; if (token.getOffset() < mentionStart) { isMeasure.add(Boolean.FALSE); continue; } else { int tokenOffsetEnd = token.getOffset() + length(token.getText()); if (token.getOffset() >= mentionStart && tokenOffsetEnd <= mentionEnd) { isMeasure.add(Boolean.TRUE); } else { isMeasure.add(Boolean.FALSE); } if (mentionId == offsets.size() - 1) { break; } else { if (tokenOffsetEnd >= mentionEnd) { mentionId++; offset = offsets.get(mentionId); } } } } if (tokens.size() > isMeasure.size()) { for (int counter = isMeasure.size(); counter < tokens.size(); counter++) { isMeasure.add(Boolean.FALSE); } } return isMeasure; } /** * Return a list of layoutToken of all the elements of the measurement **/ public static List<LayoutToken> getLayoutTokens(List<Quantity> quantities) { return quantities .stream() .flatMap(q -> { List<LayoutToken> lt = getLayoutTokens(q); return lt.stream(); }) .collect(Collectors.toList()); } public static List<LayoutToken> getLayoutTokens(Quantity q) { List<LayoutToken> lt = new ArrayList<>(q.getLayoutTokens()); if (q.getRawUnit() != null) { lt.addAll(q.getRawUnit().getLayoutTokens()); } return lt; } public static UnitUtilities.Unit_Type getType(Measurement m) { if (UnitUtilities.Measurement_Type.VALUE.equals(m.getType())) { return m.getQuantityAtomic().getType(); } else if (UnitUtilities.Measurement_Type.INTERVAL_MIN_MAX.equals(m.getType())) { Quantity quantityBase = m.getQuantityLeast(); Quantity quantityRange = m.getQuantityMost(); if (quantityBase != null && quantityBase.getType() != null) { return quantityBase.getType(); } else if (quantityRange != null && quantityRange.getType() != null) { return quantityRange.getType(); } else { return UnitUtilities.Unit_Type.UNKNOWN; } } else if (UnitUtilities.Measurement_Type.INTERVAL_BASE_RANGE.equals(m.getType())) { Quantity quantityBase = m.getQuantityBase(); Quantity quantityRange = m.getQuantityRange(); if (quantityBase != null && quantityBase.getType() != null) { return quantityBase.getType(); } else if (quantityRange != null && quantityRange.getType() != null) { return quantityRange.getType(); } else { return UnitUtilities.Unit_Type.UNKNOWN; } } else if (UnitUtilities.Measurement_Type.CONJUNCTION.equals(m.getType())) { if (isNotEmpty(m.getQuantityList())) { for(Quantity q : m.getQuantityList()) { if(q.getType() != null) { return q.getType(); } } } return UnitUtilities.Unit_Type.UNKNOWN; } throw new GrobidException("Invalid measurement, missing type"); } }
package org.grouplens.grapht.solver; import com.google.common.base.Functions; import com.google.common.base.Predicates; import com.google.common.collect.*; import org.apache.commons.lang3.tuple.Pair; import org.grouplens.grapht.graph.DAGEdge; import org.grouplens.grapht.graph.DAGNode; import org.grouplens.grapht.graph.DAGNodeBuilder; import org.grouplens.grapht.spi.CachePolicy; import org.grouplens.grapht.spi.CachedSatisfaction; import org.grouplens.grapht.spi.Desire; import org.grouplens.grapht.spi.Satisfaction; import org.grouplens.grapht.spi.reflect.AttributesImpl; import org.grouplens.grapht.spi.reflect.NullSatisfaction; import org.grouplens.grapht.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class DependencySolver { private static final Logger logger = LoggerFactory.getLogger(DependencySolver.class); public static final CachedSatisfaction ROOT_SATISFACTION = new CachedSatisfaction(new NullSatisfaction(Void.TYPE), CachePolicy.NO_PREFERENCE); /** * Get an initial injection context. * @return The context from the initial injection. */ public static InjectionContext initialContext() { return InjectionContext.singleton(ROOT_SATISFACTION.getSatisfaction(), new AttributesImpl()); } /** * Get a singleton root node for a dependency graph. * @return A root node for a dependency graph with no resolved objects. */ public static DAGNode<CachedSatisfaction,DesireChain> rootNode() { return DAGNode.singleton(ROOT_SATISFACTION); } private final int maxDepth; private final CachePolicy defaultPolicy; private final List<BindingFunction> functions; private final List<BindingFunction> triggerFunctions; private DAGNode<CachedSatisfaction,DesireChain> graph; private Set<DAGEdge<CachedSatisfaction,DesireChain>> backEdges; DependencySolver(List<BindingFunction> bindFunctions, List<BindingFunction> triggers, CachePolicy defaultPolicy, int maxDepth) { Preconditions.notNull("bindFunctions", bindFunctions); Preconditions.notNull("defaultPolicy", defaultPolicy); if (maxDepth <= 0) { throw new IllegalArgumentException("Max depth must be at least 1"); } this.functions = new ArrayList<BindingFunction>(bindFunctions); this.triggerFunctions = new ArrayList<BindingFunction>(triggers); this.maxDepth = maxDepth; this.defaultPolicy = defaultPolicy; graph = DAGNode.singleton(ROOT_SATISFACTION); backEdges = Sets.newHashSet(); logger.info("DependencySolver created, max depth: {}", maxDepth); } /** * Create a new dependency solver builder. * * @return A dependency solver builder. */ public static DependencySolverBuilder newBuilder() { return new DependencySolverBuilder(); } /** * Get the current full dependency graph. This consists of a synthetic root node with edges * to the resolutions of all dependencies passed to {@link #resolve(Desire)}. * @return The resolved dependency graph. */ public DAGNode<CachedSatisfaction,DesireChain> getGraph() { return graph; } /** * Get the map of back-edges for circular dependencies. Circular dependencies are only allowed * via provider injection, and only if {@link ProviderBindingFunction} is one of the binding * functions. In such cases, there will be a back edge from the provider node to the actual * node being provided, and this map will report that edge. * @return A snapshot of the map of back-edges. */ public ImmutableSet<DAGEdge<CachedSatisfaction, DesireChain>> getBackEdges() { return ImmutableSet.copyOf(backEdges); } /** * Get the back edge for a particular node and desire, if one exists. * @return The back edge, or {@code null} if no edge exists. * @see #getBackEdges() */ public synchronized DAGNode<CachedSatisfaction,DesireChain> getBackEdge(DAGNode<CachedSatisfaction, DesireChain> parent, Desire desire) { return FluentIterable.from(backEdges) .filter(DAGEdge.headMatches(Predicates.equalTo(parent))) .filter(DAGEdge.labelMatches(DesireChain.hasInitialDesire(desire))) .first() .transform(DAGEdge.<CachedSatisfaction, DesireChain>extractTail()) .orNull(); } /** * Get the root node. * @deprecated Use {@link #getGraph()} instead. */ @Deprecated public DAGNode<CachedSatisfaction,DesireChain> getRootNode() { return graph; } /** * Update the dependency graph to include the given desire. An edge from the * root node to the desire's resolved satisfaction will exist after this is * finished. * * @param desire The desire to include in the graph */ public synchronized void resolve(Desire desire) throws SolverException { logger.info("Resolving desire: {}", desire); Queue<Deferral> deferralQueue = new ArrayDeque<Deferral>(); // before any deferred nodes are processed, we use a synthetic root // and null original desire since nothing produced this root deferralQueue.add(new Deferral(rootNode(), initialContext())); while(!deferralQueue.isEmpty()) { Deferral current = deferralQueue.poll(); DAGNode<CachedSatisfaction, DesireChain> parent = current.node; // deferred nodes are either root - depless - or having deferred dependencies assert parent.getOutgoingEdges().isEmpty(); if (current.node.getLabel().equals(ROOT_SATISFACTION)) { DAGNodeBuilder<CachedSatisfaction,DesireChain> bld = DAGNode.copyBuilder(parent); bld.addEdge(resolveFully(desire, current.context, deferralQueue)); graph = merge(bld.build(), graph, true); } else if (graph.getReachableNodes().contains(parent)) { // the node needs to be re-scanned. This means that it was not consolidated by // a previous merge operation. This branch only arises with provider injection. Satisfaction sat = parent.getLabel().getSatisfaction(); for (Desire d: sat.getDependencies()) { logger.debug("Attempting to resolve deferred dependency {} of {}", d, sat); // resolve the dependency Pair<DAGNode<CachedSatisfaction, DesireChain>, DesireChain> result = resolveFully(d, current.context, deferralQueue); // merge it in DAGNode<CachedSatisfaction, DesireChain> merged = merge(result.getLeft(), graph, false); // now see if there's a real cycle if (merged.getReachableNodes().contains(parent)) { // parent node is referenced from merged, we have a circle! // that means we need a back edge backEdges.add(DAGEdge.create(parent, merged, result.getRight())); } else { // an edge from parent to merged does not add a cycle // we have to update graph right away so it's available to merge the next // dependency DAGNode<CachedSatisfaction, DesireChain> newP = DAGNode.copyBuilder(parent) .addEdge(merged, result.getRight()) .build(); replaceNode(parent, newP); parent = newP; } } } else { // node unreachable - it's a leftover or unneeded deferral logger.debug("node {} not in graph, ignoring", parent); } } } private void replaceNode(DAGNode<CachedSatisfaction,DesireChain> old, DAGNode<CachedSatisfaction,DesireChain> repl) { Map<DAGNode<CachedSatisfaction,DesireChain>, DAGNode<CachedSatisfaction,DesireChain>> memory = Maps.newHashMap(); graph = graph.replaceNode(old, repl, memory); // loop over a snapshot of the list, replacing nodes backEdges = Sets.newHashSet(Iterables.transform(backEdges, DAGEdge.transformNodes(Functions.forMap(memory, null)))); } /** * Merge a graph, resulting from a resolve, into the global graph. * * @param tree The unmerged tree to merge in. * @param mergeTarget The graph to merge with. * @param mergeRoot Whether to merge this with the root of the global graph. If {@code true}, * the outgoing edges of {@code tree} are added to the outgoing edges of * the root of the global graph and the resulting graph returned. * @return The new merged graph. */ private DAGNode<CachedSatisfaction,DesireChain> merge(DAGNode<CachedSatisfaction,DesireChain> tree, DAGNode<CachedSatisfaction,DesireChain> mergeTarget, boolean mergeRoot) { List<DAGNode<CachedSatisfaction, DesireChain>> sorted = tree.getSortedNodes(); Map<Pair<CachedSatisfaction,Set<DAGNode<CachedSatisfaction,DesireChain>>>, DAGNode<CachedSatisfaction,DesireChain>> nodeTable = Maps.newHashMap(); for (DAGNode<CachedSatisfaction,DesireChain> node: mergeTarget.getReachableNodes()) { Pair<CachedSatisfaction,Set<DAGNode<CachedSatisfaction,DesireChain>>> key = Pair.of(node.getLabel(), node.getAdjacentNodes()); assert !nodeTable.containsKey(key); nodeTable.put(key, node); } // Look up each node's dependencies in the merged graph, since we sorted // by reverse depth we can guarantee that dependencies have already // been merged Map<DAGNode<CachedSatisfaction,DesireChain>, DAGNode<CachedSatisfaction,DesireChain>> mergedMap = Maps.newHashMap(); for (DAGNode<CachedSatisfaction, DesireChain> toMerge: sorted) { CachedSatisfaction sat = toMerge.getLabel(); // Accumulate the set of dependencies for this node, filtering // them through the previous level map Set<DAGNode<CachedSatisfaction, DesireChain>> dependencies = FluentIterable.from(toMerge.getOutgoingEdges()) .transform(DAGEdge.<CachedSatisfaction,DesireChain>extractTail()) .transform(Functions.forMap(mergedMap)) .toSet(); DAGNode<CachedSatisfaction, DesireChain> newNode = nodeTable.get(Pair.of(sat, dependencies)); if (newNode == null) { DAGNodeBuilder<CachedSatisfaction,DesireChain> bld = DAGNode.newBuilder(); // this configuration for the satisfaction has not been seen before // - add it to merged graph, and connect to its dependencies boolean changed = false; bld.setLabel(sat); logger.debug("Adding new node to merged graph for satisfaction: {}", sat); for (DAGEdge<CachedSatisfaction, DesireChain> dep: toMerge.getOutgoingEdges()) { // add the edge with the new head and the previously merged tail // List<Desire> is downsized to the first Desire, too DAGNode<CachedSatisfaction, DesireChain> filtered = mergedMap.get(dep.getTail()); bld.addEdge(filtered, dep.getLabel()); changed |= !filtered.equals(dep.getTail()); } if (changed) { newNode = bld.build(); } else { // no edges were changed, leave the node unmodified newNode = toMerge; } nodeTable.put(Pair.of(sat, dependencies), newNode); } else { logger.debug("Node already in merged graph for satisfaction: {}", toMerge.getLabel()); } // update merge map so future nodes use this node as a dependency mergedMap.put(toMerge, newNode); } // now time to build up the last node if (mergeRoot) { DAGNodeBuilder<CachedSatisfaction,DesireChain> bld = DAGNode.copyBuilder(graph); for (DAGEdge<CachedSatisfaction,DesireChain> edge: mergedMap.get(tree).getOutgoingEdges()) { bld.addEdge(edge.getTail(), edge.getLabel()); } return bld.build(); } else { return mergedMap.get(tree); } } /** * Resolve a desire and its dependencies, inserting them into the graph. * * @param desire The desire to resolve. * @param context The context of {@code parent}. * @param deferQueue The queue of node deferrals. * @throws SolverException if there is an error resolving the nodes. */ private Pair<DAGNode<CachedSatisfaction,DesireChain>,DesireChain> resolveFully(Desire desire, InjectionContext context, Queue<Deferral> deferQueue) throws SolverException { // check context depth against max to detect likely dependency cycles if (context.size() > maxDepth) { throw new CyclicDependencyException(desire, "Maximum context depth of " + maxDepth + " was reached"); } // resolve the current node // - pair of pairs is a little awkward, but there's no triple type Resolution result = resolve(desire, context); CachedSatisfaction sat = new CachedSatisfaction(result.satisfaction, result.policy); InjectionContext newContext = context.extend(result.satisfaction, desire.getInjectionPoint().getAttributes()); DAGNode<CachedSatisfaction,DesireChain> node; if (result.deferDependencies) { // extend node onto deferred queue and skip its dependencies for now logger.debug("Deferring dependencies of {}", result.satisfaction); node = DAGNode.singleton(sat); deferQueue.add(new Deferral(node, newContext)); } else { // build up a node with its outgoing edges DAGNodeBuilder<CachedSatisfaction,DesireChain> nodeBuilder = DAGNode.newBuilder(); nodeBuilder.setLabel(sat); for (Desire d: result.satisfaction.getDependencies()) { // complete the sub graph for the given desire // - the call to resolveFully() is responsible for adding the dependency edges // so we don't need to process the returned node logger.debug("Attempting to satisfy dependency {} of {}", d, result.satisfaction); nodeBuilder.addEdge(resolveFully(d, newContext, deferQueue)); } node = nodeBuilder.build(); } return Pair.of(node, result.desires); } private Resolution resolve(Desire desire, InjectionContext context) throws SolverException { DesireChain chain = DesireChain.singleton(desire); CachePolicy policy = CachePolicy.NO_PREFERENCE; while(true) { logger.debug("Current desire: {}", chain.getCurrentDesire()); BindingResult binding = null; for (BindingFunction bf: functions) { binding = bf.bind(context, chain); if (binding != null && !chain.getPreviousDesires().contains(binding.getDesire())) { // found a binding that hasn't been used before break; } } boolean defer = false; boolean terminate = true; if (binding != null) { // update the desire chain chain = chain.extend(binding.getDesire()); terminate = binding.terminates(); defer = binding.isDeferred(); // upgrade policy if needed if (binding.getCachePolicy().compareTo(policy) > 0) { policy = binding.getCachePolicy(); } } if (terminate && chain.getCurrentDesire().isInstantiable()) { logger.info("Satisfied {} with {}", desire, chain.getCurrentDesire().getSatisfaction()); // update cache policy if a specific policy hasn't yet been selected if (policy.equals(CachePolicy.NO_PREFERENCE)) { policy = chain.getCurrentDesire().getSatisfaction().getDefaultCachePolicy(); if (policy.equals(CachePolicy.NO_PREFERENCE)) { policy = defaultPolicy; } } return new Resolution(chain.getCurrentDesire().getSatisfaction(), policy, chain, defer); } else if (binding == null) { // no more desires to process, it cannot be satisfied throw new UnresolvableDependencyException(chain, context); } } } /* * Result tuple for resolve(Desire, InjectionContext) */ private static class Resolution { private final Satisfaction satisfaction; private final CachePolicy policy; private final DesireChain desires; private final boolean deferDependencies; public Resolution(Satisfaction satisfaction, CachePolicy policy, DesireChain desires, boolean deferDependencies) { this.satisfaction = satisfaction; this.policy = policy; this.desires = desires; this.deferDependencies = deferDependencies; } } /* * Deferred results tuple */ private static class Deferral { private final DAGNode<CachedSatisfaction, DesireChain> node; private final InjectionContext context; public Deferral(DAGNode<CachedSatisfaction, DesireChain> node, InjectionContext context) { this.node = node; this.context = context; } } }
package org.jboss.aesh.console.man; import org.jboss.aesh.console.Buffer; import org.jboss.aesh.console.Config; import org.jboss.aesh.console.command.Command; import org.jboss.aesh.console.command.invocation.CommandInvocation; import org.jboss.aesh.console.command.CommandOperation; import org.jboss.aesh.console.operator.ControlOperator; import org.jboss.aesh.terminal.Key; import org.jboss.aesh.terminal.Shell; import org.jboss.aesh.util.ANSI; import org.jboss.aesh.util.LoggerUtil; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import org.jboss.aesh.console.man.TerminalPage.Search; public abstract class AeshFileDisplayer implements Command { private int rows; private int columns; private int topVisibleRow; private int topVisibleRowCache; //only rewrite page if rowCache != row private TerminalPage page; private StringBuilder number; private TerminalPage.Search search = TerminalPage.Search.NO_SEARCH; private StringBuilder searchBuilder; private List<Integer> searchLines; private static final Logger LOGGER = LoggerUtil.getLogger(AeshFileDisplayer.class.getName()); private CommandInvocation commandInvocation; private ControlOperator operation; private boolean stop; public AeshFileDisplayer() { stop = false; } protected void setCommandInvocation(CommandInvocation commandInvocation) { this.commandInvocation = commandInvocation; setControlOperator(commandInvocation.getControlOperator()); } protected CommandInvocation getCommandInvocation() { return commandInvocation; } protected void setControlOperator(ControlOperator operator) { this.operation = operator; } protected Shell getShell() { return commandInvocation.getShell(); } protected void afterAttach() throws IOException, InterruptedException { number = new StringBuilder(); searchBuilder = new StringBuilder(); rows = getShell().getSize().getHeight(); columns = getShell().getSize().getWidth(); page = new TerminalPage(getFileParser(), columns); topVisibleRow = 0; topVisibleRowCache = -1; stop = false; if(operation.isRedirectionOut()) { int count=0; for(String line : this.page.getLines()) { getShell().out().print(line); count++; if(count < this.page.size()) getShell().out().print(Config.getLineSeparator()); } getShell().out().flush(); afterDetach(); getShell().out().flush(); } else { if(!page.hasData()) { getShell().out().println("error: input is null..."); afterDetach(); } else { getShell().out().print(ANSI.getAlternateBufferScreen()); if(this.page.getFileName() != null) display(); else display(); processInput(); } } } protected void afterDetach() throws IOException { if(!operation.isRedirectionOut()) getShell().out().print(ANSI.getMainBufferScreen()); page.clear(); topVisibleRow = 0; } public void processInput() throws IOException, InterruptedException { try { while(!stop) { processOperation(getCommandInvocation().getInput()); } } catch (InterruptedException e) { afterDetach(); stop = true; throw e; } } public void processOperation(CommandOperation operation) throws IOException { if(operation.getInputKey() == Key.q) { if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else { clearNumber(); afterDetach(); stop = true; } } else if(operation.getInputKey() == Key.j || operation.getInputKey() == Key.DOWN || operation.getInputKey() == Key.DOWN_2 || operation.getInputKey() == Key.ENTER ) { if(search == Search.SEARCHING) { if(operation.getInputKey() == Key.j) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else if(operation.getInputKey() == Key.ENTER) { search = Search.RESULT; findSearchWord(true); } } else if(search == Search.NOT_FOUND) { if(operation.getInputKey() == Key.ENTER) { search = Search.NO_SEARCH; clearBottomLine(); displayBottom(); } } else { topVisibleRow = topVisibleRow + getNumber(); if(topVisibleRow > (page.size()-rows-1)) { topVisibleRow = page.size()-rows-1; if(topVisibleRow < 0) topVisibleRow = 0; display(); } else display(); clearNumber(); } } else if(operation.getInputKey() == Key.k || operation.getInputKey() == Key.UP || operation.getInputKey() == Key.UP_2) { if(search == Search.SEARCHING) { if(operation.getInputKey() == Key.k) searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else { topVisibleRow = topVisibleRow - getNumber(); if(topVisibleRow < 0) topVisibleRow = 0; display(); clearNumber(); } } else if(operation.getInputKey() == Key.CTRL_F || operation.getInputKey() == Key.PGDOWN || operation.getInputKey() == Key.SPACE) { // ctrl-f || pgdown || space if(search == Search.SEARCHING) { } else { topVisibleRow = topVisibleRow + rows*getNumber()-1; if(topVisibleRow > (page.size()-rows-1)) { topVisibleRow = page.size()-rows-1; if(topVisibleRow < 0) topVisibleRow = 0; display(); } else display(); clearNumber(); } } else if(operation.getInputKey() == Key.CTRL_B || operation.getInputKey() == Key.PGUP) { // ctrl-b || pgup if(search != Search.SEARCHING) { topVisibleRow = topVisibleRow - rows*getNumber()-1; if(topVisibleRow < 0) topVisibleRow = 0; display(); clearNumber(); } } //search else if(operation.getInputKey() == Key.SLASH) { if(search == Search.NO_SEARCH || search == Search.RESULT) { search = Search.SEARCHING; searchBuilder = new StringBuilder(); displayBottom(); } else if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } } else if(operation.getInputKey() == Key.n) { if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else if(search == Search.RESULT) { if(searchLines.size() > 0) { for(Integer i : searchLines) { if(i > topVisibleRow+1) { topVisibleRow = i-1; display(); return; } } //we didnt find any more displayBottom(); } else { displayBottom(); } } } else if(operation.getInputKey() == Key.N) { if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else if(search == Search.RESULT) { if(searchLines.size() > 0) { for(int i=searchLines.size()-1; i >= 0; i if(searchLines.get(i) < topVisibleRow) { topVisibleRow = searchLines.get(i)-1; if(topVisibleRow < 0) topVisibleRow = 0; display(); return; } } //we didnt find any more displayBottom(); } } } else if(operation.getInputKey() == Key.G) { if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else { if(number.length() == 0 || getNumber() == 0) { topVisibleRow = page.size()-rows-1; display(); } else { topVisibleRow = getNumber()-1; if(topVisibleRow > page.size()-rows-1) { topVisibleRow = page.size()-rows-1; display(); } else { display(); } } clearNumber(); } } else if(operation.getInputKey().isNumber()) { if(search == Search.SEARCHING) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } else { number.append(Character.getNumericValue(operation.getInput()[0])); display(); } } else { if(search == Search.SEARCHING && (Character.isAlphabetic(operation.getInput()[0]))) { searchBuilder.append((char) operation.getInput()[0]); displayBottom(); } } } private void display() throws IOException { if(topVisibleRow != topVisibleRowCache) { getShell().clear(); if(search == Search.RESULT && searchLines.size() > 0) { String searchWord = searchBuilder.toString(); for(int i=topVisibleRow; i < (topVisibleRow+rows-1); i++) { if(i < page.size()) { String line = page.getLine(i); if(line.contains(searchWord)) displaySearchLine(line, searchWord); else getShell().out().print(line); getShell().out().print(Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } else { for(int i=topVisibleRow; i < (topVisibleRow+rows-1); i++) { if(i < page.size()) { getShell().out().print(page.getLine(i)+ Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } displayBottom(); } getShell().out().flush(); } /** * highlight the specific word thats found in the search */ private void displaySearchLine(String line, String searchWord) throws IOException { int start = line.indexOf(searchWord); getShell().out().print(line.substring(0,start)); getShell().out().print(ANSI.getInvertedBackground()); getShell().out().print(searchWord); getShell().out().print(ANSI.reset()); getShell().out().print(line.substring(start + searchWord.length(), line.length())); getShell().out().flush(); } public abstract FileParser getFileParser(); public abstract void displayBottom() throws IOException; public void writeToConsole(String word) throws IOException { getShell().out().print(word); getShell().out().flush(); } public void clearBottomLine() throws IOException { getShell().out().print(Buffer.printAnsi("0G")); getShell().out().print(Buffer.printAnsi("2K")); getShell().out().flush(); } public boolean isAtBottom() { return topVisibleRow >= (page.size()-rows-1); } public boolean isAtTop() { return topVisibleRow == 0; } public Search getSearchStatus() { return search; } public String getSearchWord() { return searchBuilder.toString(); } public int getTopVisibleRow() { return topVisibleRow+1; } private void findSearchWord(boolean forward) throws IOException { LOGGER.info("searching for: " + searchBuilder.toString()); searchLines = page.findWord(searchBuilder.toString()); LOGGER.info("found: "+searchLines); if(searchLines.size() > 0) { for(Integer i : searchLines) if(i > topVisibleRow) { topVisibleRow = i-1; display(); return; } } else { search = Search.NOT_FOUND; displayBottom(); } } /** * number written by the user (used to jump to specific commands) */ private int getNumber() { if(number.length() > 0) return Integer.parseInt(number.toString()); else return 1; } private void clearNumber() { number = new StringBuilder(); } private static enum Background { NORMAL, INVERSE } }
package author.wizard; import java.awt.Component; import java.io.BufferedReader; //import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.JPanel; //import javax.swing.SwingUtilities; import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import constants.Constants; import util.jsonwrapper.SmartJsonObject; import util.jsonwrapper.jsonexceptions.NoJSONArrayJsonException; import util.jsonwrapper.jsonexceptions.NoJSONObjectJsonException; //import constants.Constants; //import author.listeners.FinishListener; import author.model.AuthoringCache; import author.panels.ContainerPanel; import author.panels.FinishPanel; /** * This class provides methods to dynamically * generate a Wizard based on data given in the * JSON template provided by the user. * * @author Michael Marion and Robert Ansel * */ public class WizardBuilder { public static final Map<String, String> KEYWORD_TO_PANEL_TYPE; static { Map<String, String> aMap = new HashMap<String, String>(); aMap.put(Constants.TEXT_KEYWORD, Constants.WORD_PANEL_CLASS); aMap.put(Constants.NUMBER_KEYWORD, Constants.NUMBER_PANEL_CLASS); aMap.put(Constants.FILE_URL_KEYWORD, Constants.IMAGE_PANEL_CLASS); aMap.put(Constants.RADIO_KEYWORD, Constants.RADIOBUTTON_PANEL_CLASS); aMap.put(Constants.LIST_KEYWORD, Constants.LIST_PANEL_CLASS); aMap.put(Constants.CHECKBOX_KEYWORD, Constants.CHECKBOX_PANEL_CLASS); aMap.put(Constants.MATRIX_KEYWORD, Constants.MATRIX_PANEL_CLASS); KEYWORD_TO_PANEL_TYPE = Collections.unmodifiableMap(aMap); } private String myWizardFilePath; private String myCategory; private Wizard myWizard; private AuthoringCache myCache; /** * Default constructor. Allows the user to retrieve a wizard file from * a file dialog. * */ public WizardBuilder (String category, AuthoringCache cache) { myWizard = new Wizard(category); myCategory = category; myWizardFilePath = getFilePath(); myCache = cache; addPanelsFromFile(myWizardFilePath); getConstructedWizard(); } /** * Second constructor. Allows the user to pass in the file path of * the file from which the wizard will be constructed. * */ public WizardBuilder (String category, String filePath, AuthoringCache cache) { myWizard = new Wizard(category); myCategory = category; myWizardFilePath = filePath; myCache = cache; addPanelsFromFile(myWizardFilePath); getConstructedWizard(); } private void iterateOverJSONObject (JSONObject obj, JPanel currentPanel) { JSONObject tempObject = (JSONObject) obj; Set<?> keySet = tempObject.keySet(); System.out.println(Constants.OPENING_MESSAGE + keySet); for (Object s : keySet) { if (tempObject.get(s) instanceof String) { System.out.println((String) s + Constants.STRING_STATUS_MESSAGE + tempObject.get(s) + Constants.CLOSE_PARENTHESIS); try { currentPanel.add(createPanel((String) s, (String) tempObject.get(s))); } catch (Exception e) { System.out.println(Constants.FAILED_TO_CREATE_PT1 + (String) s + Constants.FAILED_TO_CREATE_PT2 + (String) tempObject.get(s) + Constants.FAILED_TO_CREATE_PT3); e.printStackTrace(); } } else if (tempObject.get(s) instanceof JSONObject) { System.out.println((String) s + Constants.EQUALS_JSONOBJECT); handleJSONObject((String) s, (JSONObject) tempObject.get(s), currentPanel); } else if (tempObject.get(s) instanceof JSONArray) { System.out.println((String) s + Constants.EQUALS_JSONARRAY); handleJSONArray((String) s, (JSONArray) tempObject.get(s), currentPanel); } } } private void iterateOverJSONArray (JSONArray arr, JPanel currentPanel, String label) { JSONArray tempArray = ((JSONArray) arr); for (Object genericContainer : tempArray) { if (genericContainer instanceof String) { System.out.println(Constants.STRING_OPEN_PARENTHESIS + genericContainer + Constants.CLOSE_PARENTHESIS); try { currentPanel.add(createPanel("value", (String) genericContainer)); } catch (Exception e) { System.out.println(Constants.FAILED_TO_CREATE_VALUE + (String) genericContainer + Constants.FAILED_TO_CREATE_PT3); e.printStackTrace(); } } else if (genericContainer instanceof JSONObject) { System.out.println(Constants.JSONOBJECT_STRING); handleJSONObject(label, (JSONObject) genericContainer, currentPanel); } else if (genericContainer instanceof JSONArray) { System.out.println(Constants.JSONARRAY_STRING); handleJSONArray(label, (JSONArray) genericContainer, currentPanel); } } } private void handleJSONObject (String panelLabel, JSONObject object, JPanel currentPanel) { JPanel container = new ContainerPanel(panelLabel, Constants.OBJECT_STRING); currentPanel.add(container); iterateOverJSONObject(object, container); } private void handleJSONArray (String panelLabel, JSONArray arr, JPanel currentPanel) { JPanel container = new ContainerPanel(panelLabel, Constants.ARRAY_STRING); currentPanel.add(container); iterateOverJSONArray(arr, container, Constants.EMPTY_STRING); } private Component createPanel (String fieldName, String fieldType) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String[] fields = fieldType.split("_"); String basicFieldType = (fields[0].equals(Constants.LIST_KEYWORD)) ? fields[1] : fields[0]; String limitedFieldType = (fields[0].equals(Constants.LIST_KEYWORD)) ? fieldType.substring(5) : fieldType; String outputString = Constants.EMPTY_STRING; /** * We need this to be changed because it doens't work on a Mac * * The parsing with the filepath strings isn't working. * * Java has built in classes for building filepaths and file locations * - We should use those so we don't get any bugs. * * We shouldn't be parsing JSON in this class. * - Should try to use util.jsonwrapper * - Or use native Java methods (?) */ if (limitedFieldType.split("_").length > 1 && limitedFieldType.indexOf(":") == -1) { String[] locKeyPair = limitedFieldType.split("_")[1].split("\\."); JSONArray locationArray = (JSONArray) myCache.getRawJSON().get(locKeyPair[0]); outputString = "~"; for (Object con : locationArray) { outputString += (String) ((JSONObject) con).get(locKeyPair[1]) + "."; } } Class<?> classToInstantiate = Class.forName(Constants.AUTHOR_PANELS_PATH + KEYWORD_TO_PANEL_TYPE.get(basicFieldType)); Constructor<?> ctr = classToInstantiate.getConstructor(String.class); Component output = (Component) ctr.newInstance(fieldName + outputString); if (fields[0].equals(Constants.LIST_KEYWORD)) { } System.out.println(fieldName + outputString); return output; } public void addPanelsFromFile (String filePath) { JPanel currentPanel = myWizard.getCardPanel(); SmartJsonObject json = getJSON(filePath); try { JSONArray majorArray; majorArray = json.getJSONArray(myCategory); for (Object con : majorArray) { if (con instanceof JSONObject) { iterateOverJSONObject((JSONObject) con, currentPanel); } } FinishPanel finish = new FinishPanel(myCache); currentPanel.add(finish); finish.init(); } catch (NoJSONArrayJsonException e) { System.out.println(Constants.CATEGORY_NOT_FOUND_MESSAGE + myCategory + Constants.NOT_FOUND_MESSAGE); e.printStackTrace(); } } private SmartJsonObject getJSON (String filepath) { try { BufferedReader reader = new BufferedReader(new FileReader(filepath)); String line, results = Constants.EMPTY_STRING; while( ( line = reader.readLine() ) != null) { results += line; } reader.close(); return new SmartJsonObject(results); } catch (FileNotFoundException e) { System.out.println(Constants.FILE_NOT_FOUND); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoJSONObjectJsonException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(Constants.MALFORMED_JSON_MESSAGE); } return null; } /** * Get a file path from a file chooser dialog. * * @return file path of selected file. */ public String getFilePath () { // Create a new file chooser. JFileChooser fileChooser = new JFileChooser(); int returnVal = fileChooser.showOpenDialog(null); String path = null; if (returnVal == JFileChooser.APPROVE_OPTION) { File f = fileChooser.getSelectedFile(); path = f.getAbsolutePath(); } return path; } /** * Gets the constructed wizard. * * @return Wizard */ public Wizard getConstructedWizard () { return myWizard; } }
package VASSAL.launch; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JMenuBar; import org.apache.commons.lang3.SystemUtils; import VASSAL.Info; import VASSAL.build.GameModule; import VASSAL.build.module.ExtensionsLoader; import VASSAL.build.module.ModuleExtension; import VASSAL.build.module.WizardSupport; import VASSAL.build.module.metadata.AbstractMetaData; import VASSAL.build.module.metadata.MetaDataFactory; import VASSAL.build.module.metadata.ModuleMetaData; import VASSAL.i18n.Localization; import VASSAL.i18n.Resources; import VASSAL.preferences.Prefs; import VASSAL.tools.DataArchive; import VASSAL.tools.ErrorDialog; import VASSAL.tools.JarArchive; import VASSAL.tools.UsernameAndPasswordDialog; import VASSAL.tools.menu.MacOSXMenuManager; import VASSAL.tools.menu.MenuBarProxy; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.version.VersionUtils; /** * @author Joel Uckelman * @since 3.1.0 */ public class Player extends Launcher { public static void main(String[] args) throws IOException { Info.setConfig(new StandardConfig()); new Player(args); } protected Player(String[] args) { // the ctor is protected to enforce that it's called via main() super(args); } @Override protected MenuManager createMenuManager() { return SystemUtils.IS_OS_MAC ? new MacOSXMenuManager() : new PlayerMenuManager(); } @Override protected void launch() throws IOException { if (lr.builtInModule) { GameModule.init(createModule(createDataArchive())); if (lr.autoext != null) { for (final String ext : lr.autoext) { createExtension(ext).build(); } } createExtensionsLoader().addTo(GameModule.getGameModule()); Localization.getInstance().translate(); showWizardOrPlayerWindow(GameModule.getGameModule()); } else { GameModule.init(createModule(createDataArchive())); createExtensionsLoader().addTo(GameModule.getGameModule()); Localization.getInstance().translate(); final GameModule m = GameModule.getGameModule(); if (lr.game != null) { m.getPlayerWindow().setVisible(true); m.setGameFile(lr.game.getName(), GameModule.GameFileMode.LOADED_GAME); m.getGameState().loadGameInBackground(lr.game); } else { showWizardOrPlayerWindow(m); } } } protected ExtensionsLoader createExtensionsLoader() { return new ExtensionsLoader(); } protected ModuleExtension createExtension(String name) { return new ModuleExtension(new JarArchive(name)); } protected DataArchive createDataArchive() throws IOException { if (lr.builtInModule) { return new JarArchive(); } else { return new DataArchive(lr.module.getPath()); } } protected GameModule createModule(DataArchive archive) { return new GameModule(archive); } private void showWizardOrPlayerWindow(GameModule module) { module.getPlayerWindow().setVisible(true); final Boolean showWizard = (Boolean) Prefs.getGlobalPrefs().getValue(WizardSupport.WELCOME_WIZARD_KEY); if (Boolean.TRUE.equals(showWizard)) { module.getWizardSupport().showWelcomeWizard(); } else { // prompt for username and password if wizard is off // but no username is set if (!module.isRealName()) { new UsernameAndPasswordDialog(module.getPlayerWindow()).setVisible(true); } } } public static class LaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public LaunchAction(ModuleManagerWindow mm, File module) { super(Resources.getString("Main.play_module_specific"), mm, Player.class.getName(), new LaunchRequest(LaunchRequest.Mode.LOAD, module) ); setEnabled(!isEditing(module)); } public LaunchAction(ModuleManagerWindow mm, File module, File saveGame) { super(Resources.getString("General.open"), mm, Player.class.getName(), new LaunchRequest(LaunchRequest.Mode.LOAD, module, saveGame) ); setEnabled(!isEditing(module)); } @Override public void actionPerformed(ActionEvent e) { if (isEditing(lr.module)) return; // don't permit loading of VASL saved before 3.4 final AbstractMetaData data = MetaDataFactory.buildMetaData(lr.module); if (data instanceof ModuleMetaData) { final ModuleMetaData md = (ModuleMetaData) data; if (VersionUtils.compareVersions(md.getVassalVersion(), "3.4") < 0) { if ("VASL".equals(md.getName())) { //NON-NLS ErrorDialog.show( "Error.VASL_too_old", //NON-NLS Info.getVersion() ); return; } else if ("VSQL".equals(md.getName())) { //NON-NLS ErrorDialog.show( "Error.VSQL_too_old", //NON-NLS Info.getVersion() ); return; } } } else { // A module in the MM should be a valid Module, but people can and do delete // or replace module files while the MM is running. ErrorDialog.show("Error.invalid_vassal_module", lr.module.getAbsolutePath()); //NON-NLS lr.module = null; return; } // increase the using count incrementUsed(lr.module); super.actionPerformed(e); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count decrementUsed(lr.module); } }; } } public static class PromptLaunchAction extends LaunchAction { private static final long serialVersionUID = 1L; public PromptLaunchAction(ModuleManagerWindow mm) { super(mm, null); putValue(Action.NAME, Resources.getString("Main.play_module")); } @Override public void actionPerformed(ActionEvent e) { // prompt the user to pick a module if (promptForFile() == null) return; final AbstractMetaData data = MetaDataFactory.buildMetaData(lr.module); if (data != null && Info.isModuleTooNew(data.getVassalVersion())) { ErrorDialog.show( "Error.module_too_new", //NON-NLS lr.module.getPath(), data.getVassalVersion(), Info.getVersion() ); return; } super.actionPerformed(e); } } private static class PlayerMenuManager extends MenuManager { private final MenuBarProxy menuBar = new MenuBarProxy(); @Override public JMenuBar getMenuBarFor(JFrame fc) { return (fc instanceof PlayerWindow) ? menuBar.createPeer() : null; } @Override public MenuBarProxy getMenuBarProxyFor(JFrame fc) { return (fc instanceof PlayerWindow) ? menuBar : null; } } }
package org.realityforge.getopt4j; /** * Basic class describing an type of option. * Typically, one creates a static array of <code>CLOptionDescriptor</code>s, * and passes it to {@link CLArgsParser#CLArgsParser(String[], CLOptionDescriptor[])}. * * @see CLArgsParser * @see CLUtil */ public final class CLOptionDescriptor { /** * Flag to say that one argument is required */ public static final int ARGUMENT_REQUIRED = 1 << 1; /** * Flag to say that the argument is optional */ public static final int ARGUMENT_OPTIONAL = 1 << 2; /** * Flag to say this option does not take arguments */ public static final int ARGUMENT_DISALLOWED = 1 << 3; /** * Flag to say this option requires 2 arguments */ public static final int ARGUMENTS_REQUIRED_2 = 1 << 4; /** * Flag to say this option may be repeated on the command line */ public static final int DUPLICATES_ALLOWED = 1 << 5; private final int m_id; private final int m_flags; private final String m_name; private final String m_description; private final int[] m_incompatible; /** * Constructor. * * @param name the name/long option * @param flags the flags * @param id the id/character option * @param description description of option usage */ public CLOptionDescriptor( final String name, final int flags, final int id, final String description ) { this( name, flags, id, description, ( ( flags & CLOptionDescriptor.DUPLICATES_ALLOWED ) > 0 ) ? new int[ 0 ] : new int[]{ id } ); } /** * Constructor. * * @param name the name/long option * @param flags the flags * @param id the id/character option * @param description description of option usage * @param incompatible an array listing the ids of all incompatible options */ public CLOptionDescriptor( final String name, final int flags, final int id, final String description, final int[] incompatible ) { m_id = id; m_name = name; m_flags = flags; m_description = description; m_incompatible = incompatible; int modeCount = 0; if ( ( ARGUMENT_REQUIRED & flags ) == ARGUMENT_REQUIRED ) { modeCount++; } if ( ( ARGUMENT_OPTIONAL & flags ) == ARGUMENT_OPTIONAL ) { modeCount++; } if ( ( ARGUMENT_DISALLOWED & flags ) == ARGUMENT_DISALLOWED ) { modeCount++; } if ( ( ARGUMENTS_REQUIRED_2 & flags ) == ARGUMENTS_REQUIRED_2 ) { modeCount++; } if ( 0 == modeCount ) { final String message = "No mode specified for option " + this; throw new IllegalStateException( message ); } else if ( 1 != modeCount ) { final String message = "Multiple modes specified for option " + this; throw new IllegalStateException( message ); } } /** * Constructor. * * @param name the name/long option * @param flags the flags * @param id the id/character option * @param description description of option usage * @param incompatible the incompatible options. */ public CLOptionDescriptor( final String name, final int flags, final int id, final String description, final CLOptionDescriptor[] incompatible ) { m_id = id; m_name = name; m_flags = flags; m_description = description; m_incompatible = new int[ incompatible.length ]; for ( int i = 0; i < incompatible.length; i++ ) { m_incompatible[ i ] = incompatible[ i ].getId(); } } /** * @return the array of incompatible option ids * @deprecated Use the correctly spelled {@link #getIncompatible} instead. */ protected final int[] getIncompatble() { return getIncompatible(); } /** * Get the array of incompatible option ids. * * @return the array of incompatible option ids */ final int[] getIncompatible() { return m_incompatible; } /** * Retrieve textual description. * * @return the description */ public final String getDescription() { return m_description; } /** * Retrieve flags about option. * Flags include details such as whether it allows parameters etc. * * @return the flags */ public final int getFlags() { return m_flags; } /** * Retrieve the id for option. * The id is also the character if using single character options. * * @return the id */ public final int getId() { return m_id; } /** * Retrieve name of option which is also text for long option. * * @return name/long option */ public final String getName() { return m_name; } /** * Convert to String. * * @return the converted value to string. */ public final String toString() { return "[OptionDescriptor " + m_name + ", " + m_id + ", " + m_flags + ", " + m_description + " ]"; } }
package net.antonyho.jodmapper; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.DocumentFamily; import com.artofsolving.jodconverter.DocumentFormat; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import net.sf.jooreports.templates.DocumentTemplate; import net.sf.jooreports.templates.DocumentTemplateException; import net.sf.jooreports.templates.DocumentTemplateFactory; import net.sf.jooreports.templates.image.ImageSource; import net.sf.jooreports.templates.image.RenderedImageSource; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) * @throws IOException * @throws DocumentTemplateException * @throws InterruptedException */ public void testApp() throws IOException, DocumentTemplateException, InterruptedException { DocumentTemplateFactory docTemplateFactory = new DocumentTemplateFactory(); final URL odtResource = this.getClass().getResource("/template1.odt"); DocumentTemplate odtTemplate = docTemplateFactory.getTemplate(odtResource.openStream()); Map<String, Object> data = new HashMap<String, Object>(); // Referenced by variableName.fieldName using freemarker data.put("sendername", "Antony Ho"); data.put("companyname", "Antony Workshop"); data.put("addrstreet", "11-13 Tai Yuen St"); data.put("addrpostalcode", "00000"); data.put("addrcity", "Kwai Chung"); data.put("addrstate", "HK"); data.put("recipienttitle", "Lord"); data.put("recipientname", "Page Larry"); data.put("recipientstreet", "1600 Amphitheatre Parkway"); data.put("recipientpostalcode", "94043"); data.put("recipientcity", "Mountain View"); data.put("recipientstate", "CA"); /* * Add image mapping in template * 1. Add an image into proper position in the template * 2. Double click the image into the image property * 3. Go to Option tab * 4. The Name value should be: jooscript.image(image_map_key) */ ImageSource flagImg = new RenderedImageSource(ImageIO.read(this.getClass().getResource("/flag2.png"))); data.put("flag", flagImg); // generate ODT from template File odtOutput = new File("C:\\projects\\jodreports-test\\testoutput.odt"); odtTemplate.createDocument(data, new FileOutputStream(odtOutput)); // start OpenOffice/LibreOffice converter service ProcessBuilder procBuilder = new ProcessBuilder("C:/Program Files (x86)/LibreOffice 5/program/soffice.exe", "-headless", "-accept=\"socket,host=127.0.0.1,port=8100;urp;\"", "-nofirststartwizard"); Process proc = procBuilder.start(); OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100); connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); // convert ODT to PDF File pdfOutput = new File("C:\\projects\\jodreports-test\\testoutput.pdf"); converter.convert(odtOutput, pdfOutput); // convert ODT to DOC File docOutput = new File("C:\\projects\\jodreports-test\\testoutput.doc"); converter.convert(odtOutput, docOutput); // convert ODT to DOCX Not supported by JODConverter 2.2.1. Use JODConverter 2.2.2 with JAR. // File docxOutput = new File("C:\\projects\\jodreports-test\\testoutput.docx"); // final DefaultDocumentFormatRegistry docFormatRegistry = new DefaultDocumentFormatRegistry(); // converter.convert(odtOutput, docxOutput, docFormatRegistry.getFormatByMimeType("docx")); // /* // * This example is using JODConverter 2.2.1. // * In JODConverter 2.2.2, we do not need to create a DefaultDocumentFormatRegistry instance. // * OpenDocumentCoverter provides a method to getFormatRegistry. // * JODConverter 2.2.2 is not on Maven yet. // */ // converter.convert(odtOutput, docxOutput); proc.destroy(); assertTrue( true ); } }
package org.summarly.lib; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.summarly.lib.common.RankedSentence; import org.summarly.lib.common.Text; import org.summarly.lib.segmentation.LuceneSplitter; import org.summarly.lib.segmentation.StanfordNLPSplitter; import org.summarly.lib.segmentation.TextSplitter; import org.summarly.lib.summarizing.Filter; import org.summarly.lib.summarizing.LexRankRanker; import org.summarly.lib.summarizing.PreFilter; import org.summarly.lib.summarizing.modifiers.RankModifier; import org.summarly.lib.summarizing.Ranker; import org.summarly.lib.common.Sentence; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.stream.Collectors; import org.apache.tika.language.LanguageIdentifier; public class LexRankSummarizationService implements SummarizationService { private static final Logger LOGGER = LoggerFactory.getLogger(LexRankSummarizationService.class); private Ranker ranker; private TextSplitter enSplitter; private TextSplitter ruSplitter; private Filter filter; private List<RankModifier> rankModifiers; public LexRankSummarizationService() { enSplitter = new StanfordNLPSplitter(); ruSplitter = new LuceneSplitter(); ranker = new LexRankRanker(); filter = new Filter(); rankModifiers = Arrays.<RankModifier>asList(text -> text); } public List<String> summarise(String s) throws UnsupportedLanguageException { long start = System.currentTimeMillis(); Text text; PreFilter preFilter = new PreFilter(); s = preFilter.filterBrackets(s); text = splitText(s); if (text.numSentences() < 6) { throw new RuntimeException("The text is too small to apply extractive summary"); } List<RankedSentence> rankedText = ranker.rank(text); rankedText = modifyRank(rankedText); long finish = System.currentTimeMillis(); LOGGER.info(String.format( "Processed text of %d sentences in %d ms", text.numSentences(), (finish - start))); List<Sentence> summary = filter.filter(rankedText, getRatio(rankedText)) .stream().map(RankedSentence::getSentence) .collect(Collectors.<Sentence>toList()); List<String> paragraphs = buildParagraphs(summary); return paragraphs; } private List<String> buildParagraphs(List<Sentence> summary) { List<String> paragraphs = new ArrayList<String>(); StringBuilder builder = new StringBuilder(); int currentParagraph = 0; for (Sentence sentence : summary) { builder.append(sentence.getText()); if (sentence.getParagraphNum() != currentParagraph) { currentParagraph = sentence.getParagraphNum(); paragraphs.add(builder.toString()); builder.setLength(0); } else { builder.append(" "); } } return paragraphs; } private Text splitText(String s) throws UnsupportedLanguageException { Text text;LanguageIdentifier languageIdentifier = new LanguageIdentifier(s); String lang = languageIdentifier.getLanguage(); switch (lang) { case "en": text = enSplitter.split(s, ""); break; case "ru": text = ruSplitter.split(s, ""); break; default: throw new UnsupportedLanguageException(lang); } return text; } private List<RankedSentence> modifyRank(List<RankedSentence> text) { for (RankModifier modifier : rankModifiers) { text = modifier.modify(text); } return text; } protected double getRatio(List<RankedSentence> text){ return 10.0/(text.size() + 15) + 0.5; } public Ranker getRanker() { return ranker; } public void setRanker(Ranker ranker) { this.ranker = ranker; } public TextSplitter getSplitter() { return enSplitter; } public void setSplitter(TextSplitter splitter) { this.enSplitter = splitter; } }
package org.ugate.gui.components; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.SplitPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToolBar; import javafx.scene.input.MouseEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.WindowEvent; public class BeanPathAdaptorTest extends Application { ChoiceBox<String> pBox; TextArea pojoTA = new TextArea(); public static final String[] STATES = new String[]{"AK","AL","AR","AS","AZ","CA","CO", "CT","DC","DE","FL","GA","GU","HI","IA","ID","IL","IN","KS","KY","LA","MA","MD", "ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY","OH", "OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI", "WV","WY"}; private static final String P1_LABEL = "Person 1"; private static final String P2_LABEL = "Person 2"; private final Person person1 = new Person(); private final Person person2 = new Person(); private final BeanPathAdaptor<Person> personPA = new BeanPathAdaptor<Person>(person1); public static void main(final String[] args) { Application.launch(BeanPathAdaptorTest.class, args); } @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(BeanPathAdaptor.class.getSimpleName() + " TEST"); pojoTA.setFocusTraversable(false); pojoTA.setWrapText(true); pojoTA.setEditable(false); pBox = new ChoiceBox<>(FXCollections.observableArrayList( P1_LABEL, P2_LABEL)); pBox.getSelectionModel().select(0); pBox.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { personPA.setBean(newValue == P1_LABEL ? person1 : person2); } }); pBox.autosize(); ToolBar toolBar = new ToolBar(); toolBar.getItems().add(pBox); VBox personBox = new VBox(10); personBox.setPadding(new Insets(10, 10, 10, 50)); FlowPane beanPane = new FlowPane(); personBox.getChildren().addAll( new Text("Person POJO using auto-generated JavaFX properties:"), beanTF("name", 50, null, "[a-zA-z0-9\\s]*"), beanTF("age", 100, Slider.class, null), beanTF("address.street", 50, null, "[a-zA-z0-9\\s]*"), beanTF("address.location.state", 2, ChoiceBox.class, "[a-zA-z]", STATES), beanTF("address.location.country", 10, null, "[0-9]"), beanTF("address.location.international", 0, CheckBox.class, null), new Label("POJO Dump:"), pojoTA); beanPane.getChildren().addAll(personBox); final TextField pojoNameTF = new TextField(); Button pojoNameBtn = new Button("Set Person's Name"); pojoNameBtn.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { personPA.getBean().setName(pojoNameTF.getText()); dumpPojo(personPA); } }); VBox pojoBox = new VBox(10); pojoBox.setPadding(new Insets(10, 10, 10, 10)); pojoBox.getChildren().addAll(new Label("Set person's name via POJO:"), pojoNameTF, pojoNameBtn); VBox beanBox = new VBox(10); beanBox.getChildren().addAll(toolBar, beanPane); SplitPane root = new SplitPane(); root.getItems().addAll(beanBox, pojoBox); primaryStage.setOnShowing(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { dumpPojo(personPA); } }); primaryStage.setScene(new Scene(root)); primaryStage.show(); } @SafeVarargs public final void dumpPojo(final BeanPathAdaptor<Person>... ps) { Platform.runLater(new Runnable() { @Override public void run() { String dump = ""; for (BeanPathAdaptor<Person> p : ps) { dump += "Person 1 {name=" + p.getBean().getName() + ", age=" + p.getBean().getAge() + ", address.street=" + p.getBean().getAddress().getStreet() + ", address.location.state=" + p.getBean().getAddress().getLocation().getState() + ", address.location.country=" + p.getBean().getAddress().getLocation().getCountry() + ", address.location.international=" + p.getBean().getAddress().getLocation().isInternational() + "}\n"; } pojoTA.setText(dump); } }); } public <T> HBox beanTF(String path, final int maxChars, Class<? extends Control> controlType, final String restictTo, @SuppressWarnings("unchecked") T... choices) { HBox box = new HBox(); Control ctrl; if (controlType == CheckBox.class) { CheckBox cb = new CheckBox(); cb.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { dumpPojo(personPA); } }); // POJO binding magic... personPA.bindBidirectional(path, cb.selectedProperty()); ctrl = cb; } else if (controlType == ChoiceBox.class) { ChoiceBox<T> cb = new ChoiceBox<>( FXCollections.observableArrayList(choices)); cb.valueProperty().addListener(new InvalidationListener() { @Override public void invalidated(Observable observable) { dumpPojo(personPA); } }); // POJO binding magic... personPA.bindBidirectional(path, cb.valueProperty()); ctrl = cb; } else if (controlType == Slider.class) { Slider sl = new Slider(); sl.setShowTickLabels(true); sl.setShowTickMarks(true); sl.setMajorTickUnit(maxChars/2); sl.setMinorTickCount(7); sl.setBlockIncrement(1); sl.setMax(maxChars+1); sl.setSnapToTicks(true); sl.valueProperty().addListener(new InvalidationListener() { @Override public void invalidated(Observable observable) { dumpPojo(personPA); } }); // POJO binding magic... personPA.bindBidirectional(path, sl.valueProperty()); ctrl = sl; } else { final TextField tf = new TextField() { @Override public void replaceText(int start, int end, String text) { if (matchTest(text)) { super.replaceText(start, end, text); } } @Override public void replaceSelection(String text) { if (matchTest(text)) { super.replaceSelection(text); } } private boolean matchTest(String text) { return text.isEmpty() || (text.matches(restictTo) && getText().length() < maxChars); } }; tf.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { dumpPojo(personPA); } }); // POJO binding magic... personPA.bindBidirectional(path, tf.textProperty()); ctrl = tf; } box.getChildren().addAll(new Label(path + " = "), ctrl); return box; } public HBox beanTFW(String startLabel, String endLabel, TextField... tfs) { HBox box = new HBox(); box.getChildren().add(new Label(startLabel + '(')); box.getChildren().addAll(tfs); box.getChildren().add(new Label(endLabel + ");")); return box; } public static class Person { private String name; private Address address; private double age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public double getAge() { return age; } public void setAge(double age) { this.age = age; } } public static class Address { private String street; private Location location; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } } public static class Location { private int country; private String state; private Boolean isInternational; public int getCountry() { return country; } public void setCountry(int country) { this.country = country; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Boolean isInternational() { return isInternational; } public void setInternational(Boolean isInternational) { this.isInternational = isInternational; } } }
package pete.metrics.portability; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import javax.xml.transform.sax.SAXSource; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactoryConfigurationException; import net.sf.saxon.lib.NamespaceConstant; import net.sf.saxon.om.NodeInfo; import net.sf.saxon.trans.XPathException; import net.sf.saxon.xpath.XPathEvaluator; import org.xml.sax.InputSource; import pete.executables.AnalysisException; import pete.executables.FileAnalyzer; import pete.metrics.portability.assertions.BpelNamespaceContext; import pete.metrics.portability.assertions.TestAssertion; import pete.metrics.portability.assertions.TestAssertions; import pete.reporting.ReportEntry; public class PortabilityAnalyzer implements FileAnalyzer { private NodeInfo doc; private XPathEvaluator xpath; private AnalysisResult result; private void createRawResult(Path filePath) { result = new AnalysisResult(); result.setBpelFile(filePath); } private void createXPathEvaluator() throws XPathFactoryConfigurationException { XPathFactory xpathFactory = XPathFactory .newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); xpath = (XPathEvaluator) xpathFactory.newXPath(); xpath.getConfiguration().setLineNumbering(true); xpath.setNamespaceContext(new BpelNamespaceContext()); } private void createSourceDocument(String filePath) throws XPathException { InputSource inputSource = new InputSource(new File(filePath).toString()); SAXSource saxSource = new SAXSource(inputSource); doc = xpath.setSource(saxSource); } private AnalysisResult analyze() { List<TestAssertion> assertions = new TestAssertions().createAll(); for (TestAssertion assertion : assertions) { check(assertion); } computeElementNumber(); computeActivityNumber(); computeServiceActivityNumber(); return result; } private void computeElementNumber() { try { XPathExpression expr = xpath
package prospector.shootingstar.version; public class VersionUtils { public static boolean isVersionLessOrEqual(Version comparate1, Version comparate2) { if (comparate1.major > comparate2.major) { return false; } else if (comparate1.major == comparate2.major) { if (comparate1.minor > comparate2.minor) { return false; } else if (comparate1.major == comparate2.major && comparate1.minor == comparate2.minor) { if (comparate1.patch > comparate2.patch) { return false; } } return true; } return true; } }
package uk.co.CyniCode.CyniChat.Command; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import uk.co.CyniCode.CyniChat.DataManager; import uk.co.CyniCode.CyniChat.PermissionManager; import uk.co.CyniCode.CyniChat.objects.Channel; import uk.co.CyniCode.CyniChat.objects.UserDetails; /** * Class for all the admin commands * (Create and delete) * @author Matthew Ball * */ public class AdminCommand { /** * Create a channel * @param player : The player attempting to create the channel * @param name : The name of the channel * @param nick : The nickname of the channel * @param protect : Whether the channel is protected or not * @return true when complete */ public static boolean create( CommandSender player, String name, String nick, Boolean protect ) { if ( player instanceof Player ) if ( !PermissionManager.checkPerm( (Player) player, "cynichat.admin.create") ) return false; if ( DataManager.getChannel(name) != null ) { player.sendMessage("This channel is already in existance"); return true; } Channel newChan = new Channel(); if ( DataManager.hasNick( nick ) == true ) nick = name.substring(0, 2); newChan.create( name.toLowerCase(), nick.toLowerCase(), protect ); DataManager.addChannel( newChan ); player.sendMessage( "The channel: " + name + " has now been created" ); if ( player instanceof Player ) { PermissionManager.addChannelPerms( player, newChan, protect ); UserDetails current = DataManager.getOnlineDetails( (Player) player); current.joinChannel(newChan, ""); } return true; } /** * Delete the channel from the plugin * @param player : The player that's trying to execute the command * @param name : The name of the channel we're trying to delete * @return true when complete */ public static boolean remove( CommandSender player, String name ) { if ( player instanceof Player ) if ( PermissionManager.checkPerm( (Player) player, "cynichat.admin.remove") ) return false; if ( DataManager.deleteChannel( name ) == true ) { player.sendMessage("Channel has been removed"); return true; } player.sendMessage("This channel doesn't exist"); return true; } /** * Return the information on how to create a channel * @param player : The player we're returning the info for * @return true when complete */ public static boolean createInfo( CommandSender player ) { player.sendMessage(ChatColor.RED + "Incorrect Command"); player.sendMessage( "/ch create "+ChCommand.necessary("name")+" "+ChCommand.optional("nick") ); return true; } /** * Return the information on how to remove a channel * @param player : The player we're returning the info for * @return true when complete */ public static boolean removeInfo( CommandSender player ) { player.sendMessage(ChatColor.RED + "Incorrect Command"); player.sendMessage( "/ch remove "+ChCommand.necessary("name") ); return true; } }
package zmaster587.advancedRocketry; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialLiquid; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemDoor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import net.minecraftforge.registries.GameData; import zmaster587.advancedRocketry.api.AdvancedRocketryAPI; import zmaster587.advancedRocketry.api.AdvancedRocketryBiomes; import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks; import zmaster587.advancedRocketry.api.AdvancedRocketryFluids; import zmaster587.advancedRocketry.api.AdvancedRocketryItems; import zmaster587.advancedRocketry.api.Constants; import zmaster587.advancedRocketry.api.MaterialGeode; import zmaster587.advancedRocketry.api.SatelliteRegistry; import zmaster587.advancedRocketry.api.atmosphere.AtmosphereRegister; import zmaster587.advancedRocketry.api.capability.CapabilitySpaceArmor; import zmaster587.advancedRocketry.api.dimension.solar.StellarBody; import zmaster587.advancedRocketry.api.fuel.FuelRegistry; import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType; import zmaster587.advancedRocketry.api.satellite.SatelliteProperties; import zmaster587.advancedRocketry.api.stations.ISpaceObject; import zmaster587.advancedRocketry.armor.ItemSpaceArmor; import zmaster587.advancedRocketry.armor.ItemSpaceChest; import zmaster587.advancedRocketry.atmosphere.AtmosphereVacuum; import zmaster587.advancedRocketry.backwardCompat.VersionCompat; import zmaster587.advancedRocketry.block.BlockAstroBed; import zmaster587.advancedRocketry.block.BlockBeacon; import zmaster587.advancedRocketry.block.BlockCharcoalLog; import zmaster587.advancedRocketry.block.BlockCrystal; import zmaster587.advancedRocketry.block.BlockDoor2; import zmaster587.advancedRocketry.block.BlockElectricMushroom; import zmaster587.advancedRocketry.block.BlockFluid; import zmaster587.advancedRocketry.block.BlockForceField; import zmaster587.advancedRocketry.block.BlockForceFieldProjector; import zmaster587.advancedRocketry.block.BlockFuelTank; import zmaster587.advancedRocketry.block.BlockHalfTile; import zmaster587.advancedRocketry.block.BlockIntake; import zmaster587.advancedRocketry.block.BlockLandingPad; import zmaster587.advancedRocketry.block.BlockLaser; import zmaster587.advancedRocketry.block.BlockLens; import zmaster587.advancedRocketry.block.BlockLightSource; import zmaster587.advancedRocketry.block.BlockLinkedHorizontalTexture; import zmaster587.advancedRocketry.block.BlockMiningDrill; import zmaster587.advancedRocketry.block.BlockPlanetSoil; import zmaster587.advancedRocketry.block.BlockPress; import zmaster587.advancedRocketry.block.BlockPressurizedFluidTank; import zmaster587.advancedRocketry.block.BlockQuartzCrucible; import zmaster587.advancedRocketry.block.BlockRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockRocketMotor; import zmaster587.advancedRocketry.block.BlockSeal; import zmaster587.advancedRocketry.block.BlockSeat; import zmaster587.advancedRocketry.block.BlockSolarGenerator; import zmaster587.advancedRocketry.block.BlockStationModuleDockingPort; import zmaster587.advancedRocketry.block.BlockSuitWorkstation; import zmaster587.advancedRocketry.block.BlockThermiteTorch; import zmaster587.advancedRocketry.block.BlockTileNeighborUpdate; import zmaster587.advancedRocketry.block.BlockTileRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockTorchUnlit; import zmaster587.advancedRocketry.block.BlockWarpCore; import zmaster587.advancedRocketry.block.BlockWarpShipMonitor; import zmaster587.advancedRocketry.block.cable.BlockDataCable; import zmaster587.advancedRocketry.block.cable.BlockEnergyCable; import zmaster587.advancedRocketry.block.cable.BlockLiquidPipe; import zmaster587.advancedRocketry.block.multiblock.BlockARHatch; import zmaster587.advancedRocketry.block.plant.BlockAlienLeaves; import zmaster587.advancedRocketry.block.plant.BlockAlienPlank; import zmaster587.advancedRocketry.block.plant.BlockAlienSapling; import zmaster587.advancedRocketry.block.plant.BlockAlienWood; import zmaster587.advancedRocketry.capability.CapabilityProtectiveArmor; import zmaster587.advancedRocketry.command.WorldCommand; import zmaster587.advancedRocketry.common.CommonProxy; import zmaster587.advancedRocketry.dimension.DimensionManager; import zmaster587.advancedRocketry.dimension.DimensionProperties; import zmaster587.advancedRocketry.dimension.DimensionProperties.AtmosphereTypes; import zmaster587.advancedRocketry.dimension.DimensionProperties.Temps; import zmaster587.advancedRocketry.enchant.EnchantmentSpaceBreathing; import zmaster587.advancedRocketry.entity.EntityDummy; import zmaster587.advancedRocketry.entity.EntityElevatorCapsule; import zmaster587.advancedRocketry.entity.EntityItemAbducted; import zmaster587.advancedRocketry.entity.EntityLaserNode; import zmaster587.advancedRocketry.entity.EntityRocket; import zmaster587.advancedRocketry.entity.EntityStationDeployedRocket; import zmaster587.advancedRocketry.entity.EntityUIButton; import zmaster587.advancedRocketry.entity.EntityUIPlanet; import zmaster587.advancedRocketry.entity.EntityUIStar; import zmaster587.advancedRocketry.event.BucketHandler; import zmaster587.advancedRocketry.event.CableTickHandler; import zmaster587.advancedRocketry.event.PlanetEventHandler; import zmaster587.advancedRocketry.event.WorldEvents; import zmaster587.advancedRocketry.integration.CompatibilityMgr; import zmaster587.advancedRocketry.item.ItemARBucket; import zmaster587.advancedRocketry.item.ItemAsteroidChip; import zmaster587.advancedRocketry.item.ItemAstroBed; import zmaster587.advancedRocketry.item.ItemAtmosphereAnalzer; import zmaster587.advancedRocketry.item.ItemBeaconFinder; import zmaster587.advancedRocketry.item.ItemBiomeChanger; import zmaster587.advancedRocketry.item.ItemBlockCrystal; import zmaster587.advancedRocketry.item.ItemBlockFluidTank; import zmaster587.advancedRocketry.item.ItemData; import zmaster587.advancedRocketry.item.ItemJackHammer; import zmaster587.advancedRocketry.item.ItemOreScanner; import zmaster587.advancedRocketry.item.ItemPackedStructure; import zmaster587.advancedRocketry.item.ItemPlanetIdentificationChip; import zmaster587.advancedRocketry.item.ItemSatellite; import zmaster587.advancedRocketry.item.ItemSatelliteIdentificationChip; import zmaster587.advancedRocketry.item.ItemSealDetector; import zmaster587.advancedRocketry.item.ItemSpaceElevatorChip; import zmaster587.advancedRocketry.item.ItemStationChip; import zmaster587.advancedRocketry.item.ItemThermite; import zmaster587.advancedRocketry.item.components.ItemJetpack; import zmaster587.advancedRocketry.item.components.ItemPressureTank; import zmaster587.advancedRocketry.item.components.ItemUpgrade; import zmaster587.advancedRocketry.item.tools.ItemBasicLaserGun; import zmaster587.advancedRocketry.mission.MissionGasCollection; import zmaster587.advancedRocketry.mission.MissionOreMining; import zmaster587.advancedRocketry.network.PacketAsteroidInfo; import zmaster587.advancedRocketry.network.PacketAtmSync; import zmaster587.advancedRocketry.network.PacketBiomeIDChange; import zmaster587.advancedRocketry.network.PacketDimInfo; import zmaster587.advancedRocketry.network.PacketLaserGun; import zmaster587.advancedRocketry.network.PacketOxygenState; import zmaster587.advancedRocketry.network.PacketSatellite; import zmaster587.advancedRocketry.network.PacketSpaceStationInfo; import zmaster587.advancedRocketry.network.PacketStationUpdate; import zmaster587.advancedRocketry.network.PacketStellarInfo; import zmaster587.advancedRocketry.network.PacketStorageTileUpdate; import zmaster587.advancedRocketry.satellite.SatelliteBiomeChanger; import zmaster587.advancedRocketry.satellite.SatelliteComposition; import zmaster587.advancedRocketry.satellite.SatelliteDensity; import zmaster587.advancedRocketry.satellite.SatelliteEnergy; import zmaster587.advancedRocketry.satellite.SatelliteMassScanner; import zmaster587.advancedRocketry.satellite.SatelliteOptical; import zmaster587.advancedRocketry.satellite.SatelliteOreMapping; import zmaster587.advancedRocketry.stations.SpaceObject; import zmaster587.advancedRocketry.stations.SpaceObjectManager; import zmaster587.advancedRocketry.tile.TileAtmosphereDetector; import zmaster587.advancedRocketry.tile.TileDrill; import zmaster587.advancedRocketry.tile.TileFluidTank; import zmaster587.advancedRocketry.tile.TileForceFieldProjector; import zmaster587.advancedRocketry.tile.TileGuidanceComputer; import zmaster587.advancedRocketry.tile.TileRocketBuilder; import zmaster587.advancedRocketry.tile.TileSeal; import zmaster587.advancedRocketry.tile.TileSolarPanel; import zmaster587.advancedRocketry.tile.TileStationBuilder; import zmaster587.advancedRocketry.tile.TileStationDeployedAssembler; import zmaster587.advancedRocketry.tile.TileSuitWorkStation; import zmaster587.advancedRocketry.tile.Satellite.TileEntitySatelliteControlCenter; import zmaster587.advancedRocketry.tile.Satellite.TileSatelliteBuilder; import zmaster587.advancedRocketry.tile.cables.TileDataPipe; import zmaster587.advancedRocketry.tile.cables.TileEnergyPipe; import zmaster587.advancedRocketry.tile.cables.TileLiquidPipe; import zmaster587.advancedRocketry.tile.hatch.TileDataBus; import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityFuelingStation; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityMoniteringStation; import zmaster587.advancedRocketry.tile.infrastructure.TileGuidanceComputerHatch; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidUnloader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketUnloader; import zmaster587.advancedRocketry.tile.multiblock.TileAstrobodyDataProcessor; import zmaster587.advancedRocketry.tile.multiblock.TileAtmosphereTerraformer; import zmaster587.advancedRocketry.tile.multiblock.TileBeacon; import zmaster587.advancedRocketry.tile.multiblock.TileBiomeScanner; import zmaster587.advancedRocketry.tile.multiblock.TileGravityController; import zmaster587.advancedRocketry.tile.multiblock.TileObservatory; import zmaster587.advancedRocketry.tile.multiblock.TilePlanetSelector; import zmaster587.advancedRocketry.tile.multiblock.TileRailgun; import zmaster587.advancedRocketry.tile.multiblock.TileSpaceElevator; import zmaster587.advancedRocketry.tile.multiblock.TileSpaceLaser; import zmaster587.advancedRocketry.tile.multiblock.TileWarpCore; import zmaster587.advancedRocketry.tile.multiblock.energy.TileMicrowaveReciever; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; import zmaster587.advancedRocketry.tile.oxygen.TileCO2Scrubber; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenCharger; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenVent; import zmaster587.advancedRocketry.tile.station.TileDockingPort; import zmaster587.advancedRocketry.tile.station.TileLandingPad; import zmaster587.advancedRocketry.tile.station.TilePlanetaryHologram; import zmaster587.advancedRocketry.tile.station.TileStationAltitudeController; import zmaster587.advancedRocketry.tile.station.TileStationGravityController; import zmaster587.advancedRocketry.tile.station.TileStationOrientationControl; import zmaster587.advancedRocketry.tile.station.TileWarpShipMonitor; import zmaster587.advancedRocketry.util.AsteroidSmall; import zmaster587.advancedRocketry.util.FluidColored; import zmaster587.advancedRocketry.util.GravityHandler; import zmaster587.advancedRocketry.util.OreGenProperties; import zmaster587.advancedRocketry.util.RecipeHandler; import zmaster587.advancedRocketry.util.SealableBlockHandler; import zmaster587.advancedRocketry.util.XMLAsteroidLoader; import zmaster587.advancedRocketry.util.XMLOreLoader; import zmaster587.advancedRocketry.util.XMLPlanetLoader; import zmaster587.advancedRocketry.util.XMLPlanetLoader.DimensionPropertyCoupling; import zmaster587.advancedRocketry.world.biome.BiomeGenAlienForest; import zmaster587.advancedRocketry.world.biome.BiomeGenCrystal; import zmaster587.advancedRocketry.world.biome.BiomeGenDeepSwamp; import zmaster587.advancedRocketry.world.biome.BiomeGenHotDryRock; import zmaster587.advancedRocketry.world.biome.BiomeGenMarsh; import zmaster587.advancedRocketry.world.biome.BiomeGenMoon; import zmaster587.advancedRocketry.world.biome.BiomeGenOceanSpires; import zmaster587.advancedRocketry.world.biome.BiomeGenSpace; import zmaster587.advancedRocketry.world.biome.BiomeGenStormland; import zmaster587.advancedRocketry.world.decoration.MapGenLander; import zmaster587.advancedRocketry.world.ore.OreGenerator; import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet; import zmaster587.advancedRocketry.world.type.WorldTypePlanetGen; import zmaster587.advancedRocketry.world.type.WorldTypeSpace; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.LibVulpesBlocks; import zmaster587.libVulpes.api.LibVulpesItems; import zmaster587.libVulpes.api.material.AllowedProducts; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.api.material.MixedMaterial; import zmaster587.libVulpes.block.BlockAlphaTexture; import zmaster587.libVulpes.block.BlockMeta; import zmaster587.libVulpes.block.BlockMotor; import zmaster587.libVulpes.block.BlockTile; import zmaster587.libVulpes.block.multiblock.BlockMultiBlockComponentVisible; import zmaster587.libVulpes.block.multiblock.BlockMultiblockMachine; import zmaster587.libVulpes.inventory.GuiHandler; import zmaster587.libVulpes.items.ItemBlockMeta; import zmaster587.libVulpes.items.ItemIngredient; import zmaster587.libVulpes.items.ItemProjector; import zmaster587.libVulpes.network.PacketHandler; import zmaster587.libVulpes.network.PacketItemModifcation; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.TileMaterial; import zmaster587.libVulpes.tile.multiblock.TileMultiBlock; import zmaster587.libVulpes.util.HashedBlockPosition; import zmaster587.libVulpes.util.InputSyncHandler; import zmaster587.libVulpes.util.SingleEntry; @Mod(modid="advancedrocketry", name="Advanced Rocketry", version="@MAJOR@.@MINOR@.@REVIS@.@BUILD@", dependencies="required-after:libvulpes@[%LIBVULPESVERSION%,)") public class AdvancedRocketry { @SidedProxy(clientSide="zmaster587.advancedRocketry.client.ClientProxy", serverSide="zmaster587.advancedRocketry.common.CommonProxy") public static CommonProxy proxy; public final static String version = "@MAJOR@.@MINOR@.@REVIS@@BUILD@"; @Instance(value = Constants.modId) public static AdvancedRocketry instance; public static WorldType planetWorldType; public static WorldType spaceWorldType; public static final RecipeHandler machineRecipes = new RecipeHandler(); final String oreGen = "Ore Generation"; final String ROCKET = "Rockets"; final String MOD_INTERACTION = "Mod Interaction"; final String PLANET = "Planet"; final String ASTEROID = "Asteroid"; final String GAS_MINING = "GasMining"; final String PERFORMANCE = "Performance"; public static CompatibilityMgr compat = new CompatibilityMgr(); public static Logger logger = LogManager.getLogger(Constants.modId); private static Configuration config; private static final String BIOMECATETORY = "Biomes"; private boolean resetFromXml; String[] sealableBlockWhiteList, breakableTorches, harvestableGasses, entityList, asteriodOres, geodeOres, orbitalLaserOres, liquidRocketFuel; //static { // FluidRegistry.enableUniversalBucket(); // Must be called before preInit public static MaterialRegistry materialRegistry = new MaterialRegistry(); public static HashMap<AllowedProducts, HashSet<String>> modProducts = new HashMap<AllowedProducts, HashSet<String>>(); private static CreativeTabs tabAdvRocketry = new CreativeTabs("advancedRocketry") { @Override public ItemStack getTabIconItem() { return new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip); } }; //Biome registry. @SubscribeEvent public void register(RegistryEvent.Register<Biome> evt) { System.out.println("REGISTERING BIOMES"); AdvancedRocketryBiomes.moonBiome = new BiomeGenMoon(config.get(BIOMECATETORY, "moonBiomeId", 110).getInt(), true); AdvancedRocketryBiomes.alienForest = new BiomeGenAlienForest(config.get(BIOMECATETORY, "alienForestBiomeId", 111).getInt(), true); AdvancedRocketryBiomes.hotDryBiome = new BiomeGenHotDryRock(config.get(BIOMECATETORY, "hotDryBiome", 112).getInt(), true); AdvancedRocketryBiomes.spaceBiome = new BiomeGenSpace(config.get(BIOMECATETORY, "spaceBiomeId", 113).getInt(), true); AdvancedRocketryBiomes.stormLandsBiome = new BiomeGenStormland(config.get(BIOMECATETORY, "stormLandsBiomeId", 114).getInt(), true); AdvancedRocketryBiomes.crystalChasms = new BiomeGenCrystal(config.get(BIOMECATETORY, "crystalChasmsBiomeId", 115).getInt(), true); AdvancedRocketryBiomes.swampDeepBiome = new BiomeGenDeepSwamp(config.get(BIOMECATETORY, "deepSwampBiomeId", 116).getInt(), true); AdvancedRocketryBiomes.marsh = new BiomeGenMarsh(config.get(BIOMECATETORY, "marsh", 117).getInt(), true); AdvancedRocketryBiomes.oceanSpires = new BiomeGenOceanSpires(config.get(BIOMECATETORY, "oceanSpires", 118).getInt(), true); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.moonBiome, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.alienForest, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.hotDryBiome, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.spaceBiome, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.stormLandsBiome, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.crystalChasms, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.swampDeepBiome, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.marsh, evt.getRegistry()); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.oceanSpires, evt.getRegistry()); } @EventHandler public void preInit(FMLPreInitializationEvent event) { //Init API DimensionManager.planetWorldProvider = WorldProviderPlanet.class; AdvancedRocketryAPI.atomsphereSealHandler = SealableBlockHandler.INSTANCE; ((SealableBlockHandler)AdvancedRocketryAPI.atomsphereSealHandler).loadDefaultData(); config = new Configuration(new File(event.getModConfigurationDirectory(), "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/advancedRocketry.cfg")); config.load(); AtmosphereVacuum.damageValue = (int) config.get(Configuration.CATEGORY_GENERAL, "vacuumDamage", 1, "Amount of damage taken every second in a vacuum").getInt(); zmaster587.advancedRocketry.api.Configuration.buildSpeedMultiplier = (float) config.get(Configuration.CATEGORY_GENERAL, "buildSpeedMultiplier", 1f, "Multiplier for the build speed of the Rocket Builder (0.5 is twice as fast 2 is half as fast").getDouble(); zmaster587.advancedRocketry.api.Configuration.spaceDimId = config.get(Configuration.CATEGORY_GENERAL,"spaceStationId" , -2,"Dimension ID to use for space stations").getInt(); zmaster587.advancedRocketry.api.Configuration.enableOxygen = config.get(Configuration.CATEGORY_GENERAL, "EnableAtmosphericEffects", true, "If true, allows players being hurt due to lack of oxygen and allows effects from non-standard atmosphere types").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods = config.get(Configuration.CATEGORY_GENERAL, "makeMaterialsForOtherMods", true, "If true the machines from AdvancedRocketry will produce things like plates/rods for other mods even if Advanced Rocketry itself does not use the material (This can increase load time)").getBoolean(); zmaster587.advancedRocketry.api.Configuration.scrubberRequiresCartrige = config.get(Configuration.CATEGORY_GENERAL, "scrubberRequiresCartrige", true, "If true the Oxygen scrubbers require a consumable carbon collection cartridge").getBoolean(); zmaster587.advancedRocketry.api.Configuration.enableLaserDrill = config.get(Configuration.CATEGORY_GENERAL, "EnableLaserDrill", true, "Enables the laser drill machine").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceLaserPowerMult = (float)config.get(Configuration.CATEGORY_GENERAL, "LaserDrillPowerMultiplier", 1d, "Power multiplier for the laser drill machine").getDouble(); zmaster587.advancedRocketry.api.Configuration.lowGravityBoots = config.get(Configuration.CATEGORY_GENERAL, "lowGravityBoots", false, "If true the boots only protect the player on planets with low gravity").getBoolean(); zmaster587.advancedRocketry.api.Configuration.jetPackThrust = (float)config.get(Configuration.CATEGORY_GENERAL, "jetPackForce", 1.3, "Amount of force the jetpack provides with respect to gravity, 1 is the same acceleration as caused by Earth's gravity, 2 is 2x the acceleration caused by Earth's gravity, etc. To make jetpack only work on low gravity planets, simply set it to a value less than 1").getDouble(); int spaceBreathingId = config.get(Configuration.CATEGORY_GENERAL, "AirtightSealEnchantID", 128, "Enchantment ID for the airtight seal effect").getInt(); zmaster587.advancedRocketry.api.Configuration.enableTerraforming = config.get(Configuration.CATEGORY_GENERAL, "EnableTerraforming", true,"Enables terraforming items and blocks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.oxygenVentPowerMultiplier = config.get(Configuration.CATEGORY_GENERAL, "OxygenVentPowerMultiplier", 1.0f, "Power consumption multiplier for the oxygen vent", 0, Float.MAX_VALUE).getDouble(); zmaster587.advancedRocketry.api.Configuration.spaceSuitOxygenTime = config.get(Configuration.CATEGORY_GENERAL, "spaceSuitO2Buffer", 30, "Maximum time in minutes that the spacesuit's internal buffer can store O2 for").getInt(); zmaster587.advancedRocketry.api.Configuration.travelTimeMultiplier = (float)config.get(Configuration.CATEGORY_GENERAL, "warpTravelTime", 1f, "Multiplier for warp travel time").getDouble(); zmaster587.advancedRocketry.api.Configuration.maxBiomesPerPlanet = config.get(Configuration.CATEGORY_GENERAL, "maxBiomesPerPlanet", 5, "Maximum unique biomes per planet, -1 to disable").getInt(); zmaster587.advancedRocketry.api.Configuration.allowTerraforming = config.get(Configuration.CATEGORY_GENERAL, "allowTerraforming", false, "EXPERIMENTAL: If set to true allows contruction and usage of the terraformer. This is known to cause strange world generation after successful terraform").getBoolean(); zmaster587.advancedRocketry.api.Configuration.terraformingBlockSpeed = config.get(Configuration.CATEGORY_GENERAL, "biomeUpdateSpeed", 1, "How many blocks have the biome changed per tick. Large numbers can slow the server down", Integer.MAX_VALUE, 1).getInt(); zmaster587.advancedRocketry.api.Configuration.terraformSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformMult", 1f, "Multplier for atmosphere change speed").getDouble(); zmaster587.advancedRocketry.api.Configuration.terraformPlanetSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformBlockPerTick", 1, "Max number of blocks allowed to be changed per tick").getInt(); zmaster587.advancedRocketry.api.Configuration.terraformRequiresFluid = config.get(Configuration.CATEGORY_GENERAL, "TerraformerRequiresFluids", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.terraformliquidRate = config.get(Configuration.CATEGORY_GENERAL, "TerraformerFluidConsumeRate", 40, "how many millibuckets/t are required to keep the terraformer running").getInt(); liquidRocketFuel = config.get(ROCKET, "rocketFuels", new String[] {"rocketfuel"}, "List of fluid names for fluids that can be used as rocket fuel").getStringList(); zmaster587.advancedRocketry.api.Configuration.stationSize = config.get(Configuration.CATEGORY_GENERAL, "SpaceStationBuildRadius", 1024, "The largest size a space station can be. Should also be a power of 2 (512, 1024, 2048, 4096, ...). CAUTION: CHANGING THIS OPTION WILL DAMAGE EXISTING STATIONS!!!").getInt(); zmaster587.advancedRocketry.api.Configuration.canPlayerRespawnInSpace = config.get(Configuration.CATEGORY_GENERAL, "allowPlanetRespawn", false, "If true players will respawn near beds on planets IF the spawn location is in a breathable atmosphere").getBoolean(); zmaster587.advancedRocketry.api.Configuration.solarGeneratorMult = config.get(Configuration.CATEGORY_GENERAL, "solarGeneratorMultiplier", 1, "Amount of power per tick the solar generator should produce").getInt(); zmaster587.advancedRocketry.api.Configuration.enableGravityController = config.get(Configuration.CATEGORY_GENERAL, "enableGravityMachine", true, "If false the gravity controller cannot be built or used").getBoolean(); zmaster587.advancedRocketry.api.Configuration.planetsMustBeDiscovered = config.get(Configuration.CATEGORY_GENERAL, "planetsMustBeDiscovered", false, "If true planets must be discovered in the warp controller before being visible").getBoolean(); zmaster587.advancedRocketry.api.Configuration.dropExTorches = config.get(Configuration.CATEGORY_GENERAL, "dropExtinguishedTorches", false, "If true, breaking an extinguished torch will drop an extinguished torch instead of a vanilla torch").getBoolean(); DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 8000, "Dimensions including and after this number are allowed to be made into planets"); zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes = config.getBoolean("blackListVanillaBiomes", PLANET, false, "Prevents any vanilla biomes from spawning on planets"); zmaster587.advancedRocketry.api.Configuration.overrideGCAir = config.get(MOD_INTERACTION, "OverrideGCAir", true, "If true Galaciticcraft's air will be disabled entirely requiring use of Advanced Rocketry's Oxygen system on GC planets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.fuelPointsPerDilithium = config.get(Configuration.CATEGORY_GENERAL, "pointsPerDilithium", 500, "How many units of fuel should each Dilithium Crystal give to warp ships", 1, 1000).getInt(); zmaster587.advancedRocketry.api.Configuration.electricPlantsSpawnLightning = config.get(Configuration.CATEGORY_GENERAL, "electricPlantsSpawnLightning", true, "Should Electric Mushrooms be able to spawn lightning").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood = config.get(Configuration.CATEGORY_GENERAL, "sawMillCutVanillaWood", true, "Should the cutting machine be able to cut vanilla wood into planks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.automaticRetroRockets = config.get(ROCKET, "autoRetroRockets", true, "Setting to false will disable the retrorockets that fire automatically on reentry on both player and automated rockets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.atmosphereHandleBitMask = config.get(PERFORMANCE, "atmosphereCalculationMethod", 0, "BitMask: 0: no threading, radius based; 1: threading, radius based (EXP); 2: no threading volume based; 3: threading volume based (EXP)").getInt(); zmaster587.advancedRocketry.api.Configuration.oxygenVentSize = config.get(PERFORMANCE, "oxygenVentSize", 32, "Radius of the O2 vent. if atmosphereCalculationMethod is 2 or 3 then max volume is calculated from this radius. WARNING: larger numbers can lead to lag").getInt(); zmaster587.advancedRocketry.api.Configuration.oxygenVentConsumptionMult = config.get(Configuration.CATEGORY_GENERAL, "oxygenVentConsumptionMultiplier", 1f, "Multiplier on how much O2 an oxygen vent consumes per tick").getDouble(); zmaster587.advancedRocketry.api.Configuration.gravityAffectsFuel = config.get(Configuration.CATEGORY_GENERAL, "gravityAffectsFuels", true, "If true planets with higher gravity require more fuel and lower gravity would require less").getBoolean(); zmaster587.advancedRocketry.api.Configuration.advancedVFX = config.get(PERFORMANCE, "advancedVFX", true, "Advanced visual effects").getBoolean(); zmaster587.advancedRocketry.api.Configuration.gasCollectionMult = config.get(GAS_MINING, "gasMissionMultiplier", 1.0, "Multiplier for the amount of time gas collection missions take").getDouble(); zmaster587.advancedRocketry.api.Configuration.asteroidMiningTimeMult = config.get(ASTEROID, "miningMissionTmeMultiplier", 1.0, "Multiplier changing how long a mining mission takes").getDouble(); asteriodOres = config.get(ASTEROID, "standardOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in asteriods").getStringList(); geodeOres = config.get(oreGen, "geodeOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in geodes").getStringList(); zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList = config.get(oreGen, "geodeOres_blacklist", false, "True if the ores in geodeOres should be a blacklist, false for whitelist").getBoolean(); zmaster587.advancedRocketry.api.Configuration.generateGeodes = config.get(oreGen, "generateGeodes", true, "If true then ore-containing geodes are generated on high pressure planets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.geodeBaseSize = config.get(oreGen, "geodeBaseSize", 36, "average size of the geodes").getInt(); zmaster587.advancedRocketry.api.Configuration.geodeVariation = config.get(oreGen, "geodeVariation", 24, "variation in geode size").getInt(); zmaster587.advancedRocketry.api.Configuration.planetDiscoveryChance = config.get(PLANET, "planetDiscoveryChance", 5, "Chance of planet discovery in the warp ship monitor is not all planets are initially discoved, chance is 1/n", 1, Integer.MAX_VALUE).getInt(); orbitalLaserOres = config.get(Configuration.CATEGORY_GENERAL, "laserDrillOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone", "oreDiamond"}, "List of oredictionary names of ores allowed to be mined by the laser drill if surface drilling is disabled. Ores can be specified by just the oreName:<size> or by <modname>:<blockname>:<meta>:<size> where size is optional").getStringList(); zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList = config.get(Configuration.CATEGORY_GENERAL, "laserDrillOres_blacklist", false, "True if the ores in laserDrillOres should be a blacklist, false for whitelist").getBoolean(); zmaster587.advancedRocketry.api.Configuration.laserDrillPlanet = config.get(Configuration.CATEGORY_GENERAL, "laserDrillPlanet", false, "If true the orbital laser will actually mine blocks on the planet below").getBoolean(); resetFromXml = config.getBoolean("resetPlanetsFromXML", Configuration.CATEGORY_GENERAL, false, "setting this to true will DELETE existing advancedrocketry planets and regen the solar system from the advanced planet XML file, satellites orbiting the overworld will remain intact and stations will be moved to the overworld."); //Reset to false config.get(Configuration.CATEGORY_GENERAL, "resetPlanetsFromXML",false).set(false); //Client zmaster587.advancedRocketry.api.Configuration.rocketRequireFuel = config.get(ROCKET, "rocketsRequireFuel", true, "Set to false if rockets should not require fuel to fly").getBoolean(); zmaster587.advancedRocketry.api.Configuration.rocketThrustMultiplier = config.get(ROCKET, "thrustMultiplier", 1f, "Multiplier for per-engine thrust").getDouble(); zmaster587.advancedRocketry.api.Configuration.fuelCapacityMultiplier = config.get(ROCKET, "fuelCapacityMultiplier", 1f, "Multiplier for per-tank capacity").getDouble(); //Copper Config zmaster587.advancedRocketry.api.Configuration.generateCopper = config.get(oreGen, "GenerateCopper", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.copperClumpSize = config.get(oreGen, "CopperPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.copperPerChunk = config.get(oreGen, "CopperPerChunk", 10).getInt(); //Tin Config zmaster587.advancedRocketry.api.Configuration.generateTin = config.get(oreGen, "GenerateTin", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.tinClumpSize = config.get(oreGen, "TinPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.tinPerChunk = config.get(oreGen, "TinPerChunk", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateDilithium = config.get(oreGen, "generateDilithium", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.dilithiumClumpSize = config.get(oreGen, "DilithiumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunk = config.get(oreGen, "DilithiumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunkMoon = config.get(oreGen, "DilithiumPerChunkLuna", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateAluminum = config.get(oreGen, "generateAluminum", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.aluminumClumpSize = config.get(oreGen, "AluminumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.aluminumPerChunk = config.get(oreGen, "AluminumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.generateRutile = config.get(oreGen, "GenerateRutile", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.rutileClumpSize = config.get(oreGen, "RutilePerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.rutilePerChunk = config.get(oreGen, "RutilePerChunk", 6).getInt(); sealableBlockWhiteList = config.getStringList(Configuration.CATEGORY_GENERAL, "sealableBlockWhiteList", new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); breakableTorches = config.getStringList("torchBlocks", Configuration.CATEGORY_GENERAL, new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); harvestableGasses = config.getStringList("harvestableGasses", GAS_MINING, new String[] {}, "list of fluid names that can be harvested as Gas"); entityList = config.getStringList("entityAtmBypass", Configuration.CATEGORY_GENERAL, new String[] {}, "list entities which should not be affected by atmosphere properties"); //Satellite config zmaster587.advancedRocketry.api.Configuration.microwaveRecieverMulitplier = 10*(float)config.get(Configuration.CATEGORY_GENERAL, "MicrowaveRecieverMultiplier", 1f, "Multiplier for the amount of energy produced by the microwave reciever").getDouble(); String str[] = config.getStringList("spaceLaserDimIdBlackList", Configuration.CATEGORY_GENERAL, new String[] {}, "Laser drill will not mine these dimension"); //Load laser dimid blacklists for(String s : str) { try { zmaster587.advancedRocketry.api.Configuration.laserBlackListDims.add(Integer.parseInt(s)); } catch (NumberFormatException e) { logger.warn("Invalid number \"" + s + "\" for laser dimid blacklist"); } } //Load client and UI positioning stuff proxy.loadUILayout(config); config.save(); //Register cap events MinecraftForge.EVENT_BUS.register(new CapabilityProtectiveArmor()); //Register Packets PacketHandler.INSTANCE.addDiscriminator(PacketDimInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketSatellite.class); PacketHandler.INSTANCE.addDiscriminator(PacketStellarInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketItemModifcation.class); PacketHandler.INSTANCE.addDiscriminator(PacketOxygenState.class); PacketHandler.INSTANCE.addDiscriminator(PacketStationUpdate.class); PacketHandler.INSTANCE.addDiscriminator(PacketSpaceStationInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketAtmSync.class); PacketHandler.INSTANCE.addDiscriminator(PacketBiomeIDChange.class); PacketHandler.INSTANCE.addDiscriminator(PacketStorageTileUpdate.class); PacketHandler.INSTANCE.addDiscriminator(PacketLaserGun.class); PacketHandler.INSTANCE.addDiscriminator(PacketAsteroidInfo.class); //if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) MinecraftForge.EVENT_BUS.register(this); SatelliteRegistry.registerSatellite("optical", SatelliteOptical.class); SatelliteRegistry.registerSatellite("solar", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("density", SatelliteDensity.class); SatelliteRegistry.registerSatellite("composition", SatelliteComposition.class); SatelliteRegistry.registerSatellite("mass", SatelliteMassScanner.class); SatelliteRegistry.registerSatellite("asteroidMiner", MissionOreMining.class); SatelliteRegistry.registerSatellite("gasMining", MissionGasCollection.class); SatelliteRegistry.registerSatellite("solarEnergy", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("oreScanner", SatelliteOreMapping.class); SatelliteRegistry.registerSatellite("biomeChanger", SatelliteBiomeChanger.class); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "mountDummy"),EntityDummy.class, "mountDummy", 0, this, 16, 20, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "rocket") ,EntityRocket.class, "rocket", 1, this, 64, 3, true); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "laserNode"), EntityLaserNode.class, "laserNode", 2, instance, 256, 20, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "deployedRocket"), EntityStationDeployedRocket.class, "deployedRocket", 3, this, 256, 600, true); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "ARAbductedItem"), EntityItemAbducted.class, "ARAbductedItem", 4, this, 127, 600, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "ARPlanetUIItem"), EntityUIPlanet.class, "ARPlanetUIItem", 5, this, 64, 1, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "ARPlanetUIButton"), EntityUIButton.class, "ARPlanetUIButton", 6, this, 64, 20, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "ARStarUIButton"), EntityUIStar.class, "ARStarUIButton", 7, this, 64, 20, false); EntityRegistry.registerModEntity(new ResourceLocation(Constants.modId, "ARSpaceElevatorCapsule"),EntityElevatorCapsule.class, "ARSpaceElevatorCapsule", 8, this, 64, 20, true); GameRegistry.registerTileEntity(TileRocketBuilder.class, "ARrocketBuilder"); GameRegistry.registerTileEntity(TileWarpCore.class, "ARwarpCore"); //GameRegistry.registerTileEntity(TileModelRender.class, "ARmodelRenderer"); GameRegistry.registerTileEntity(TileEntityFuelingStation.class, "ARfuelingStation"); GameRegistry.registerTileEntity(TileEntityMoniteringStation.class, "ARmonitoringStation"); //GameRegistry.registerTileEntity(TileMissionController.class, "ARmissionControlComp"); GameRegistry.registerTileEntity(TileSpaceLaser.class, "ARspaceLaser"); GameRegistry.registerTileEntity(TilePrecisionAssembler.class, "ARprecisionAssembler"); GameRegistry.registerTileEntity(TileObservatory.class, "ARobservatory"); GameRegistry.registerTileEntity(TileCrystallizer.class, "ARcrystallizer"); GameRegistry.registerTileEntity(TileCuttingMachine.class, "ARcuttingmachine"); GameRegistry.registerTileEntity(TileDataBus.class, "ARdataBus"); GameRegistry.registerTileEntity(TileSatelliteHatch.class, "ARsatelliteHatch"); GameRegistry.registerTileEntity(TileGuidanceComputerHatch.class, "ARguidanceComputerHatch"); GameRegistry.registerTileEntity(TileSatelliteBuilder.class, "ARsatelliteBuilder"); GameRegistry.registerTileEntity(TileEntitySatelliteControlCenter.class, "ARTileEntitySatelliteControlCenter"); GameRegistry.registerTileEntity(TileAstrobodyDataProcessor.class, "ARplanetAnalyser"); GameRegistry.registerTileEntity(TileGuidanceComputer.class, "ARguidanceComputer"); GameRegistry.registerTileEntity(TileElectricArcFurnace.class, "ARelectricArcFurnace"); GameRegistry.registerTileEntity(TilePlanetSelector.class, "ARTilePlanetSelector"); //GameRegistry.registerTileEntity(TileModelRenderRotatable.class, "ARTileModelRenderRotatable"); GameRegistry.registerTileEntity(TileMaterial.class, "ARTileMaterial"); GameRegistry.registerTileEntity(TileLathe.class, "ARTileLathe"); GameRegistry.registerTileEntity(TileRollingMachine.class, "ARTileMetalBender"); GameRegistry.registerTileEntity(TileStationBuilder.class, "ARStationBuilder"); GameRegistry.registerTileEntity(TileElectrolyser.class, "ARElectrolyser"); GameRegistry.registerTileEntity(TileChemicalReactor.class, "ARChemicalReactor"); GameRegistry.registerTileEntity(TileOxygenVent.class, "AROxygenVent"); GameRegistry.registerTileEntity(TileOxygenCharger.class, "AROxygenCharger"); GameRegistry.registerTileEntity(TileCO2Scrubber.class, "ARCO2Scrubber"); GameRegistry.registerTileEntity(TileWarpShipMonitor.class, "ARStationMonitor"); GameRegistry.registerTileEntity(TileAtmosphereDetector.class, "AROxygenDetector"); GameRegistry.registerTileEntity(TileStationOrientationControl.class, "AROrientationControl"); GameRegistry.registerTileEntity(TileStationGravityController.class, "ARGravityControl"); GameRegistry.registerTileEntity(TileLiquidPipe.class, "ARLiquidPipe"); GameRegistry.registerTileEntity(TileDataPipe.class, "ARDataPipe"); GameRegistry.registerTileEntity(TileEnergyPipe.class, "AREnergyPipe"); GameRegistry.registerTileEntity(TileDrill.class, "ARDrill"); GameRegistry.registerTileEntity(TileMicrowaveReciever.class, "ARMicrowaveReciever"); GameRegistry.registerTileEntity(TileSuitWorkStation.class, "ARSuitWorkStation"); GameRegistry.registerTileEntity(TileRocketLoader.class, "ARRocketLoader"); GameRegistry.registerTileEntity(TileRocketUnloader.class, "ARRocketUnloader"); GameRegistry.registerTileEntity(TileBiomeScanner.class, "ARBiomeScanner"); GameRegistry.registerTileEntity(TileAtmosphereTerraformer.class, "ARAttTerraformer"); GameRegistry.registerTileEntity(TileLandingPad.class, "ARLandingPad"); GameRegistry.registerTileEntity(TileStationDeployedAssembler.class, "ARStationDeployableRocketAssembler"); GameRegistry.registerTileEntity(TileFluidTank.class, "ARFluidTank"); GameRegistry.registerTileEntity(TileRocketFluidUnloader.class, "ARFluidUnloader"); GameRegistry.registerTileEntity(TileRocketFluidLoader.class, "ARFluidLoader"); GameRegistry.registerTileEntity(TileSolarPanel.class, "ARSolarGenerator"); GameRegistry.registerTileEntity(TileDockingPort.class, "ARDockingPort"); GameRegistry.registerTileEntity(TileStationAltitudeController.class, "ARStationAltitudeController"); GameRegistry.registerTileEntity(TileRailgun.class, "ARRailgun"); GameRegistry.registerTileEntity(TilePlanetaryHologram.class, "ARplanetHoloSelector"); GameRegistry.registerTileEntity(TileForceFieldProjector.class, "ARForceFieldProjector"); GameRegistry.registerTileEntity(TileSeal.class, "ARBlockSeal"); GameRegistry.registerTileEntity(TileSpaceElevator.class, "ARSpaceElevator"); GameRegistry.registerTileEntity(TileBeacon.class, "ARBeacon"); if(zmaster587.advancedRocketry.api.Configuration.enableGravityController) GameRegistry.registerTileEntity(TileGravityController.class, "ARGravityMachine"); //Register machine recipes LibVulpes.registerRecipeHandler(TileCuttingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/CuttingMachine.xml"); LibVulpes.registerRecipeHandler(TilePrecisionAssembler.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/PrecisionAssembler.xml"); LibVulpes.registerRecipeHandler(TileChemicalReactor.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ChemicalReactor.xml"); LibVulpes.registerRecipeHandler(TileCrystallizer.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Crystallizer.xml"); LibVulpes.registerRecipeHandler(TileElectrolyser.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Electrolyser.xml"); LibVulpes.registerRecipeHandler(TileElectricArcFurnace.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ElectricArcFurnace.xml"); LibVulpes.registerRecipeHandler(TileLathe.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Lathe.xml"); LibVulpes.registerRecipeHandler(TileRollingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/RollingMachine.xml"); LibVulpes.registerRecipeHandler(BlockPress.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/SmallPlatePress.xml"); //Enchantments AdvancedRocketryAPI.enchantmentSpaceProtection = new EnchantmentSpaceBreathing(); AdvancedRocketryAPI.enchantmentSpaceProtection.setRegistryName(new ResourceLocation("advancedrocketry:spacebreathing")); GameData.register_impl(AdvancedRocketryAPI.enchantmentSpaceProtection); //AUDIO //Register Space Objects SpaceObjectManager.getSpaceManager().registerSpaceObjectType("genericObject", SpaceObject.class); //Regiser item/block crap proxy.preinit(); } @SubscribeEvent(priority=EventPriority.HIGH) public void registerItems(RegistryEvent.Register<Item> evt) { AdvancedRocketryItems.itemWafer = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:wafer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCircuitPlate = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:circuitplate").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemIC = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:circuitIC").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemMisc = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:miscpart").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSawBlade = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:sawBlade").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStationChip = new ItemStationChip().setUnlocalizedName("stationChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceElevatorChip = new ItemSpaceElevatorChip().setUnlocalizedName("elevatorChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemAsteroidChip = new ItemAsteroidChip().setUnlocalizedName("asteroidChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStation = new ItemPackedStructure().setUnlocalizedName("station"); AdvancedRocketryItems.itemSmallAirlockDoor = new ItemDoor(AdvancedRocketryBlocks.blockAirLock).setUnlocalizedName("smallAirlock").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCarbonScrubberCartridge = new Item().setMaxDamage(Short.MAX_VALUE).setUnlocalizedName("carbonScrubberCartridge").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemLens = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:lens").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePowerSource = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:satellitePowerSource").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePrimaryFunction = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:satellitePrimaryFunction").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemThermite = new ItemThermite().setUnlocalizedName("thermite").setCreativeTab(tabAdvRocketry); //TODO: move registration in the case we have more than one chip type AdvancedRocketryItems.itemDataUnit = new ItemData().setUnlocalizedName("advancedrocketry:dataUnit").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemOreScanner = new ItemOreScanner().setUnlocalizedName("OreScanner").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemQuartzCrucible = new ItemBlock(AdvancedRocketryBlocks.blockQuartzCrucible).setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellite = new ItemSatellite().setUnlocalizedName("satellite").setCreativeTab(tabAdvRocketry).setMaxStackSize(1); AdvancedRocketryItems.itemSatelliteIdChip = new ItemSatelliteIdentificationChip().setUnlocalizedName("satelliteIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemPlanetIdChip = new ItemPlanetIdentificationChip().setUnlocalizedName("planetIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBiomeChanger = new ItemBiomeChanger().setUnlocalizedName("biomeChanger").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBasicLaserGun = new ItemBasicLaserGun().setUnlocalizedName("basicLaserGun").setCreativeTab(tabAdvRocketry); //Fluids AdvancedRocketryItems.itemBucketRocketFuel = new ItemARBucket(AdvancedRocketryFluids.fluidRocketFuel).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketRocketFuel").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketNitrogen = new ItemARBucket(AdvancedRocketryFluids.fluidNitrogen).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketNitrogen").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketHydrogen = new ItemARBucket(AdvancedRocketryFluids.fluidHydrogen).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketHydrogen").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketOxygen = new ItemARBucket(AdvancedRocketryFluids.fluidOxygen).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketOxygen").setContainerItem(Items.BUCKET); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidHydrogen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidNitrogen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidOxygen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidRocketFuel); //Suit Component Registration AdvancedRocketryItems.itemJetpack = new ItemJetpack().setCreativeTab(tabAdvRocketry).setUnlocalizedName("jetPack"); AdvancedRocketryItems.itemPressureTank = new ItemPressureTank(4, 1000).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:pressureTank"); AdvancedRocketryItems.itemUpgrade = new ItemUpgrade(5).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:itemUpgrade"); AdvancedRocketryItems.itemAtmAnalyser = new ItemAtmosphereAnalzer().setCreativeTab(tabAdvRocketry).setUnlocalizedName("atmAnalyser"); AdvancedRocketryItems.itemBeaconFinder = new ItemBeaconFinder().setCreativeTab(tabAdvRocketry).setUnlocalizedName("beaconFinder"); //Armor registration AdvancedRocketryItems.itemSpaceSuit_Helmet = new ItemSpaceArmor(ArmorMaterial.LEATHER, EntityEquipmentSlot.HEAD,4).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceHelmet"); AdvancedRocketryItems.itemSpaceSuit_Chest = new ItemSpaceChest(ArmorMaterial.LEATHER, EntityEquipmentSlot.CHEST,6).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceChest"); AdvancedRocketryItems.itemSpaceSuit_Leggings = new ItemSpaceArmor(ArmorMaterial.LEATHER, EntityEquipmentSlot.LEGS,4).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceLeggings"); AdvancedRocketryItems.itemSpaceSuit_Boots = new ItemSpaceArmor(ArmorMaterial.LEATHER, EntityEquipmentSlot.FEET,4).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceBoots"); AdvancedRocketryItems.itemSealDetector = new ItemSealDetector().setMaxStackSize(1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sealDetector"); //Tools AdvancedRocketryItems.itemJackhammer = new ItemJackHammer(ToolMaterial.DIAMOND).setUnlocalizedName("jackhammer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("jackhammer", 3); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("pickaxe", 3); //Note: not registered AdvancedRocketryItems.itemAstroBed = new ItemAstroBed(); //Register Satellite Properties SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOptical.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteComposition.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteMassScanner.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteEnergy.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOreMapping.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteBiomeChanger.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), new SatelliteProperties().setPowerGeneration(1)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1), new SatelliteProperties().setPowerGeneration(10)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 0), new SatelliteProperties().setPowerStorage(100)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 1), new SatelliteProperties().setPowerStorage(400)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), new SatelliteProperties().setMaxData(1000)); //Item Registration LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemQuartzCrucible.setRegistryName("iquartzcrucible")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemOreScanner.setRegistryName("oreScanner")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePowerSource.setRegistryName("satellitePowerSource")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePrimaryFunction.setRegistryName("satellitePrimaryFunction")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCircuitPlate.setRegistryName("itemCircuitPlate")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemIC.setRegistryName("ic")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemWafer.setRegistryName("wafer")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemDataUnit.setRegistryName("dataUnit")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellite.setRegistryName("satellite")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatelliteIdChip.setRegistryName("satelliteIdChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPlanetIdChip.setRegistryName("planetIdChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemMisc.setRegistryName("misc")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSawBlade.setRegistryName("sawBladeIron")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStationChip.setRegistryName("spaceStationChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStation.setRegistryName("spaceStation")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Helmet.setRegistryName("spaceHelmet")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Boots.setRegistryName("spaceBoots")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Chest.setRegistryName("spaceChestplate")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Leggings.setRegistryName("spaceLeggings")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketRocketFuel.setRegistryName("bucketRocketFuel")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketNitrogen.setRegistryName("bucketNitrogen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketHydrogen.setRegistryName("bucketHydrogen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketOxygen.setRegistryName("bucketOxygen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSmallAirlockDoor.setRegistryName("smallAirlockDoor")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCarbonScrubberCartridge.setRegistryName("carbonScrubberCartridge")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSealDetector.setRegistryName("sealDetector")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJackhammer.setRegistryName("jackHammer")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAsteroidChip.setRegistryName("asteroidChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceElevatorChip.setRegistryName("elevatorChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemLens.setRegistryName("lens")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJetpack.setRegistryName("jetPack")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPressureTank.setRegistryName("pressureTank")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemUpgrade.setRegistryName("itemUpgrade")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAtmAnalyser.setRegistryName("atmAnalyser")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBasicLaserGun.setRegistryName("basicLaserGun")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBeaconFinder.setRegistryName("beaconFinder")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemThermite.setRegistryName("thermite")); if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming) LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBiomeChanger.setRegistryName("biomeChanger")); //End Items proxy.preInitItems(); } @SubscribeEvent(priority=EventPriority.HIGH) public void registerBlocks(RegistryEvent.Register<Block> evt) { AdvancedRocketryBlocks.blocksGeode = new Block(MaterialGeode.geode).setUnlocalizedName("geode").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(6f).setResistance(2000F); AdvancedRocketryBlocks.blocksGeode.setHarvestLevel("jackhammer", 2); AdvancedRocketryBlocks.blockLaunchpad = new BlockLinkedHorizontalTexture(Material.ROCK).setUnlocalizedName("pad").setCreativeTab(tabAdvRocketry).setHardness(2f).setResistance(10f); AdvancedRocketryBlocks.blockStructureTower = new BlockAlphaTexture(Material.ROCK).setUnlocalizedName("structuretower").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockGenericSeat = new BlockSeat(Material.CLOTH).setUnlocalizedName("seat").setCreativeTab(tabAdvRocketry).setHardness(0.5f); AdvancedRocketryBlocks.blockEngine = new BlockRocketMotor(Material.ROCK).setUnlocalizedName("rocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAdvEngine = new BlockRocketMotor(Material.ROCK).setUnlocalizedName("advRocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockFuelTank = new BlockFuelTank(Material.ROCK).setUnlocalizedName("fuelTank").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockSawBlade = new BlockMotor(Material.ROCK,1f).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sawBlade").setHardness(2f); AdvancedRocketryBlocks.blockConcrete = new Block(Material.ROCK).setUnlocalizedName("concrete").setCreativeTab(tabAdvRocketry).setHardness(3f).setResistance(16f); AdvancedRocketryBlocks.blockPlatePress = new BlockPress().setUnlocalizedName("blockHandPress").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAirLock = new BlockDoor2(Material.ROCK).setUnlocalizedName("smallAirlockDoor").setHardness(3f).setResistance(8f); AdvancedRocketryBlocks.blockLandingPad = new BlockLandingPad(Material.ROCK).setUnlocalizedName("dockingPad").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenDetection = new BlockRedstoneEmitter(Material.ROCK,"advancedrocketry:atmosphereDetector_active").setUnlocalizedName("atmosphereDetector").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenScrubber = new BlockTile(TileCO2Scrubber.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("scrubber").setHardness(3f); AdvancedRocketryBlocks.blockUnlitTorch = new BlockTorchUnlit().setHardness(0.0F).setUnlocalizedName("unlittorch"); AdvancedRocketryBlocks.blockVitrifiedSand = new Block(Material.SAND).setUnlocalizedName("vitrifiedSand").setCreativeTab(CreativeTabs.BUILDING_BLOCKS).setHardness(0.5F); AdvancedRocketryBlocks.blockCharcoalLog = new BlockCharcoalLog().setUnlocalizedName("charcoallog").setCreativeTab(CreativeTabs.BUILDING_BLOCKS); AdvancedRocketryBlocks.blockElectricMushroom = new BlockElectricMushroom().setUnlocalizedName("electricMushroom").setCreativeTab(tabAdvRocketry).setHardness(0.0F); AdvancedRocketryBlocks.blockCrystal = new BlockCrystal().setUnlocalizedName("crystal").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(2f); AdvancedRocketryBlocks.blockOrientationController = new BlockTile(TileStationOrientationControl.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("orientationControl").setHardness(3f); AdvancedRocketryBlocks.blockGravityController = new BlockTile(TileStationGravityController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("gravityControl").setHardness(3f); AdvancedRocketryBlocks.blockAltitudeController = new BlockTile(TileStationAltitudeController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("altitudeController").setHardness(3f); AdvancedRocketryBlocks.blockOxygenCharger = new BlockHalfTile(TileOxygenCharger.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenCharger").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockOxygenVent = new BlockTile(TileOxygenVent.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenVent").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCircleLight = new Block(Material.IRON).setUnlocalizedName("circleLight").setCreativeTab(tabAdvRocketry).setHardness(2f).setLightLevel(1f); AdvancedRocketryBlocks.blockLens = new BlockLens().setUnlocalizedName("lens").setCreativeTab(tabAdvRocketry).setHardness(0.3f); AdvancedRocketryBlocks.blockRocketBuilder = new BlockTile(TileRocketBuilder.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("rocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockForceField = new BlockForceField(Material.ROCK).setBlockUnbreakable().setResistance(6000000.0F).setUnlocalizedName("forceField"); AdvancedRocketryBlocks.blockForceFieldProjector = new BlockForceFieldProjector(Material.ROCK).setUnlocalizedName("forceFieldProjector").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockDeployableRocketBuilder = new BlockTile(TileStationDeployedAssembler.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("deployableRocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockStationBuilder = new BlockTile(TileStationBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("stationAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockFuelingStation = new BlockTileRedstoneEmitter(TileEntityFuelingStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("fuelStation").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMonitoringStation = new BlockTileNeighborUpdate(TileEntityMoniteringStation.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMonitoringStation.setUnlocalizedName("monitoringstation"); AdvancedRocketryBlocks.blockWarpShipMonitor = new BlockWarpShipMonitor(TileWarpShipMonitor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockWarpShipMonitor.setUnlocalizedName("stationmonitor"); AdvancedRocketryBlocks.blockSatelliteBuilder = new BlockMultiblockMachine(TileSatelliteBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSatelliteBuilder.setUnlocalizedName("satelliteBuilder"); AdvancedRocketryBlocks.blockSatelliteControlCenter = new BlockTile(TileEntitySatelliteControlCenter.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSatelliteControlCenter.setUnlocalizedName("satelliteMonitor"); AdvancedRocketryBlocks.blockMicrowaveReciever = new BlockMultiblockMachine(TileMicrowaveReciever.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMicrowaveReciever.setUnlocalizedName("microwaveReciever"); //Arcfurnace AdvancedRocketryBlocks.blockArcFurnace = new BlockMultiblockMachine(TileElectricArcFurnace.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electricArcFurnace").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMoonTurf = new BlockPlanetSoil().setMapColor(MapColor.SNOW).setHardness(0.5F).setUnlocalizedName("turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockHotTurf = new BlockPlanetSoil().setMapColor(MapColor.NETHERRACK).setHardness(0.5F).setUnlocalizedName("hotDryturf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockLoader = new BlockARHatch(Material.ROCK).setUnlocalizedName("loader").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienWood = new BlockAlienWood().setUnlocalizedName("log").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienLeaves = new BlockAlienLeaves().setUnlocalizedName("leaves2").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienSapling = new BlockAlienSapling().setUnlocalizedName("sapling").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienPlanks = new BlockAlienPlank().setUnlocalizedName("planks").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLightSource = new BlockLightSource(); AdvancedRocketryBlocks.blockBlastBrick = new BlockMultiBlockComponentVisible(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("blastBrick").setHardness(3F).setResistance(15F); AdvancedRocketryBlocks.blockQuartzCrucible = new BlockQuartzCrucible().setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockAstroBed = new BlockAstroBed().setHardness(0.2F).setUnlocalizedName("astroBed"); AdvancedRocketryBlocks.blockPrecisionAssembler = new BlockMultiblockMachine(TilePrecisionAssembler.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("precisionAssemblingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCuttingMachine = new BlockMultiblockMachine(TileCuttingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("cuttingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCrystallizer = new BlockMultiblockMachine(TileCrystallizer.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("Crystallizer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockWarpCore = new BlockWarpCore(TileWarpCore.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("warpCore").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockChemicalReactor = new BlockMultiblockMachine(TileChemicalReactor.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("chemreactor").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLathe = new BlockMultiblockMachine(TileLathe.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("lathe").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockRollingMachine = new BlockMultiblockMachine(TileRollingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("rollingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockElectrolyser = new BlockMultiblockMachine(TileElectrolyser.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electrolyser").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAtmosphereTerraformer = new BlockMultiblockMachine(TileAtmosphereTerraformer.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("atmosphereTerraformer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPlanetAnalyser = new BlockMultiblockMachine(TileAstrobodyDataProcessor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("planetanalyser").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockObservatory = (BlockMultiblockMachine) new BlockMultiblockMachine(TileObservatory.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("observatory").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockGuidanceComputer = new BlockTile(TileGuidanceComputer.class,GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("guidanceComputer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPlanetSelector = new BlockTile(TilePlanetSelector.class,GuiHandler.guiId.MODULARFULLSCREEN.ordinal()).setUnlocalizedName("planetSelector").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPlanetHoloSelector = new BlockHalfTile(TilePlanetaryHologram.class,GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("planetHoloSelector").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockBiomeScanner = new BlockMultiblockMachine(TileBiomeScanner.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("biomeScanner").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockDrill = new BlockMiningDrill().setUnlocalizedName("drill").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSuitWorkStation = new BlockSuitWorkstation(TileSuitWorkStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("suitWorkStation").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockRailgun = new BlockMultiblockMachine(TileRailgun.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("railgun").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSpaceElevatorController = new BlockMultiblockMachine(TileSpaceElevator.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceElevatorController").setHardness(3f); AdvancedRocketryBlocks.blockBeacon = new BlockBeacon(TileBeacon.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("beacon").setHardness(3f); AdvancedRocketryBlocks.blockIntake = new BlockIntake(Material.IRON).setUnlocalizedName("gasIntake").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPressureTank = new BlockPressurizedFluidTank(Material.IRON).setUnlocalizedName("pressurizedTank").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarPanel = new Block(Material.IRON).setUnlocalizedName("solarPanel").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarGenerator = new BlockSolarGenerator(TileSolarPanel.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f).setUnlocalizedName("solarGenerator"); AdvancedRocketryBlocks.blockDockingPort = new BlockStationModuleDockingPort(Material.IRON).setUnlocalizedName("stationMarker").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPipeSealer = new BlockSeal(Material.IRON).setUnlocalizedName("pipeSeal").setCreativeTab(tabAdvRocketry).setHardness(0.5f); AdvancedRocketryBlocks.blockThermiteTorch = new BlockThermiteTorch().setUnlocalizedName("thermiteTorch").setCreativeTab(tabAdvRocketry).setHardness(0.1f).setLightLevel(1f); //Configurable stuff if(zmaster587.advancedRocketry.api.Configuration.enableGravityController) AdvancedRocketryBlocks.blockGravityMachine = new BlockMultiblockMachine(TileGravityController.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("gravityMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { AdvancedRocketryBlocks.blockSpaceLaser = new BlockLaser().setHardness(2f); AdvancedRocketryBlocks.blockSpaceLaser.setCreativeTab(tabAdvRocketry); } //Fluid Registration AdvancedRocketryFluids.fluidOxygen = new FluidColored("oxygen",0x8f94b9).setUnlocalizedName("oxygen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidOxygen)) { AdvancedRocketryFluids.fluidOxygen = FluidRegistry.getFluid("oxygen"); } AdvancedRocketryFluids.fluidHydrogen = new FluidColored("hydrogen",0xdbc1c1).setUnlocalizedName("hydrogen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidHydrogen)) { AdvancedRocketryFluids.fluidHydrogen = FluidRegistry.getFluid("hydrogen"); } AdvancedRocketryFluids.fluidRocketFuel = new FluidColored("rocketFuel", 0xe5d884).setUnlocalizedName("rocketFuel").setGaseous(false); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidRocketFuel)) { AdvancedRocketryFluids.fluidRocketFuel = FluidRegistry.getFluid("rocketFuel"); } AdvancedRocketryFluids.fluidNitrogen = new FluidColored("nitrogen", 0x97a7e7); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidNitrogen)) { AdvancedRocketryFluids.fluidNitrogen = FluidRegistry.getFluid("nitrogen"); } AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidNitrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidHydrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidOxygen); AdvancedRocketryBlocks.blockOxygenFluid = new BlockFluid(AdvancedRocketryFluids.fluidOxygen, Material.WATER).setUnlocalizedName("oxygenFluidBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockHydrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidHydrogen, Material.WATER).setUnlocalizedName("hydrogenFluidBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockFuelFluid = new BlockFluid(AdvancedRocketryFluids.fluidRocketFuel, new MaterialLiquid(MapColor.YELLOW)).setUnlocalizedName("rocketFuelBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockNitrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidNitrogen, Material.WATER).setUnlocalizedName("nitrogenFluidBlock").setCreativeTab(CreativeTabs.MISC); //Cables AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.IRON).setUnlocalizedName("liquidPipe").setCreativeTab(tabAdvRocketry).setHardness(1f); AdvancedRocketryBlocks.blockDataPipe = new BlockDataCable(Material.IRON).setUnlocalizedName("dataPipe").setCreativeTab(tabAdvRocketry).setHardness(1f); AdvancedRocketryBlocks.blockEnergyPipe = new BlockEnergyCable(Material.IRON).setUnlocalizedName("energyPipe").setCreativeTab(tabAdvRocketry).setHardness(1f); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDataPipe.setRegistryName("dataPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEnergyPipe.setRegistryName("energyPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFluidPipe.setRegistryName("liquidPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLaunchpad.setRegistryName("launchpad")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRocketBuilder.setRegistryName("rocketBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStructureTower.setRegistryName("structureTower")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGenericSeat.setRegistryName("seat")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEngine.setRegistryName("rocketmotor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAdvEngine.setRegistryName("advRocketmotor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelTank.setRegistryName("fuelTank")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelingStation.setRegistryName("fuelingStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMonitoringStation.setRegistryName("monitoringStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteBuilder.setRegistryName("satelliteBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMoonTurf.setRegistryName("moonTurf")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHotTurf.setRegistryName("hotTurf")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLoader.setRegistryName("loader"), ItemBlockMeta.class, false); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPrecisionAssembler.setRegistryName("precisionassemblingmachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBlastBrick.setRegistryName("blastBrick")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockQuartzCrucible.setRegistryName("quartzcrucible")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystallizer.setRegistryName("crystallizer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCuttingMachine.setRegistryName("cuttingMachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienWood.setRegistryName("alienWood")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienLeaves.setRegistryName("alienLeaves")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienSapling.setRegistryName("alienSapling")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockObservatory.setRegistryName("observatory")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockConcrete.setRegistryName("concrete")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetSelector.setRegistryName("planetSelector")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteControlCenter.setRegistryName("satelliteControlCenter")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetAnalyser.setRegistryName("planetAnalyser")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGuidanceComputer.setRegistryName("guidanceComputer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockArcFurnace.setRegistryName("arcFurnace")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSawBlade.setRegistryName("sawBlade")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLathe.setRegistryName("lathe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRollingMachine.setRegistryName("rollingMachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlatePress.setRegistryName("platePress")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStationBuilder.setRegistryName("stationBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectrolyser.setRegistryName("electrolyser")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockChemicalReactor.setRegistryName("chemicalReactor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenScrubber.setRegistryName("oxygenScrubber")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenVent.setRegistryName("oxygenVent")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenCharger.setRegistryName("oxygenCharger")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAirLock.setRegistryName("airlock_door")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLandingPad.setRegistryName("landingPad")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpCore.setRegistryName("warpCore")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpShipMonitor.setRegistryName("warpMonitor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenDetection.setRegistryName("oxygenDetection")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockUnlitTorch.setRegistryName("unlitTorch")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blocksGeode.setRegistryName("geode")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenFluid.setRegistryName("oxygenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHydrogenFluid.setRegistryName("hydrogenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelFluid.setRegistryName("rocketFuel")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockNitrogenFluid.setRegistryName("nitrogenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockVitrifiedSand.setRegistryName("vitrifiedSand")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCharcoalLog.setRegistryName("charcoalLog")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectricMushroom.setRegistryName("electricMushroom")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystal.setRegistryName("crystal"), ItemBlockCrystal.class, true ); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOrientationController.setRegistryName("orientationController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGravityController.setRegistryName("gravityController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDrill.setRegistryName("drill")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMicrowaveReciever.setRegistryName("microwaveReciever")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLightSource.setRegistryName("lightSource")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarPanel.setRegistryName("solarPanel")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSuitWorkStation.setRegistryName("suitWorkStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBiomeScanner.setRegistryName("biomeScanner")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAtmosphereTerraformer.setRegistryName("terraformer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDeployableRocketBuilder.setRegistryName("deployableRocketBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPressureTank.setRegistryName("liquidTank"), ItemBlockFluidTank.class, true); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockIntake.setRegistryName("intake")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCircleLight.setRegistryName("circleLight")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarGenerator.setRegistryName("solarGenerator")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDockingPort.setRegistryName("stationMarker")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAltitudeController.setRegistryName("altitudeController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRailgun .setRegistryName("railgun")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAstroBed .setRegistryName("astroBed")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetHoloSelector.setRegistryName("planetHoloSelector")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLens.setRegistryName("blockLens")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockForceField.setRegistryName("forceField")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockForceFieldProjector.setRegistryName("forceFieldProjector")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPipeSealer.setRegistryName("pipeSealer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSpaceElevatorController.setRegistryName("spaceElevatorController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBeacon.setRegistryName("beacon")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienPlanks.setRegistryName("planks")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockThermiteTorch.setRegistryName("thermiteTorch")); if(zmaster587.advancedRocketry.api.Configuration.enableGravityController) LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGravityMachine.setRegistryName("gravityMachine")); //TODO, use different mechanism to enable/disable drill if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSpaceLaser.setRegistryName("spaceLaser")); //Register Allowed Products materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumAluminide", "pickaxe", 1, 0xaec2de, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumIridium", "pickaxe", 1, 0xd7dfe4, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerOres(LibVulpes.tabLibVulpesOres); proxy.preInitBlocks(); } @EventHandler public void registerRecipes(FMLInitializationEvent evt) { List<net.minecraft.item.crafting.IRecipe> toRegister = Lists.newArrayList(); ItemStack userInterface = new ItemStack(AdvancedRocketryItems.itemMisc, 1,0); ItemStack basicCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,0); ItemStack advancedCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,2); ItemStack controlCircuitBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,3); ItemStack itemIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,4); ItemStack liquidIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,5); ItemStack trackingCircuit = new ItemStack(AdvancedRocketryItems.itemIC,1,1); ItemStack opticalSensor = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0); ItemStack massDetector = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2); ItemStack biomeChanger = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5); ItemStack smallSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0); ItemStack largeSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1); ItemStack smallBattery = new ItemStack(LibVulpesItems.itemBattery,1,0); ItemStack battery2x = new ItemStack(LibVulpesItems.itemBattery,1,1); ItemStack superHighPressureTime = new ItemStack(AdvancedRocketryItems.itemPressureTank,1,3); ItemStack charcoal = new ItemStack(Items.COAL,1,1); //TODO recipes. toRegister.add(new ShapedOreRecipe(null, new ItemStack(LibVulpesItems.itemLinker), "x","y","z", 'x', Items.REDSTONE, 'y', Items.GOLD_INGOT, 'z', Items.IRON_INGOT). setRegistryName(new ResourceLocation("libvulpes", "itemlinker"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(LibVulpesBlocks.blockHatch,1,0), new ItemStack(LibVulpesBlocks.blockHatch,1,1)). setRegistryName(new ResourceLocation("libvulpes", "blockhatchdir01"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockBlastBrick,16), new ItemStack(Items.MAGMA_CREAM,1), new ItemStack(Items.MAGMA_CREAM,1), Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK). setRegistryName(new ResourceLocation("advancedrocketry", "blockBlastBrick"))); toRegister.add(new ShapedOreRecipe(null,new ItemStack(AdvancedRocketryBlocks.blockArcFurnace), "aga","ice", "aba", 'a', Items.NETHERBRICK, 'g', userInterface, 'i', itemIOBoard, 'e',controlCircuitBoard, 'c', AdvancedRocketryBlocks.blockBlastBrick, 'b', "ingotCopper"). setRegistryName(new ResourceLocation("advancedrocketry", "blockArcFurnace"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemQuartzCrucible), " a ", "aba", " a ", Character.valueOf('a'), Items.QUARTZ, Character.valueOf('b'), Items.CAULDRON). setRegistryName(new ResourceLocation("advancedrocketry", "itemQuartzCrucible"))); toRegister.add(new ShapedOreRecipe(null, MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK"), 4), "x ", " x ", " x", 'x', "ingotIron"). setRegistryName(new ResourceLocation("advancedrocketry", "ironstick"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockPlatePress, " ", " a ", "iii", 'a', Blocks.PISTON, 'i', "ingotIron"). setRegistryName(new ResourceLocation("advancedrocketry", "blockPlatePress"))); GameRegistry.addSmelting(MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("ORE")), MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("DUST")), 0); // //Supporting Materials toRegister.add(new ShapedOreRecipe(null, userInterface, "lrl", "fgf", 'l', "dyeLime", 'r', "dustRedstone", 'g', Blocks.GLASS_PANE, 'f', Items.GLOWSTONE_DUST). setRegistryName(new ResourceLocation("advancedrocketry", "userInterface"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockGenericSeat), "xxx", 'x', Blocks.WOOL). setRegistryName(new ResourceLocation("advancedrocketry", "blockGenericSeat"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockConcrete, 16), Blocks.SAND, Blocks.GRAVEL, Items.WATER_BUCKET). setRegistryName(new ResourceLocation("advancedrocketry", "blockConcrete"))); toRegister.add(new ShapelessOreRecipe(null, AdvancedRocketryBlocks.blockLaunchpad, "concrete", "dyeBlack", "dyeYellow"). setRegistryName(new ResourceLocation("advancedrocketry", "blockLaunchpad"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockStructureTower, 8), "ooo", " o ", "ooo", 'o', "stickSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "blockStructureTower"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockEngine, "sss", " t ","t t", 's', "ingotSteel", 't', "plateTitanium"). setRegistryName(new ResourceLocation("advancedrocketry", "blockEngine"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockAdvEngine, "sss", " t ","t t", 's', "ingotTitaniumAluminide", 't', "plateTitaniumIridium"). setRegistryName(new ResourceLocation("advancedrocketry", "blockAdvEngine"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockFuelTank, "s s", "p p", "s s", 'p', "plateSteel", 's', "stickSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "blockFuelTank"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(LibVulpesItems.itemBattery,4,0), " c ","prp", "prp", 'c', "stickIron", 'r', "dustRedstone", 'p', "plateTin"). setRegistryName(new ResourceLocation("advancedrocketry", "itemBattery40"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(LibVulpesItems.itemBattery,1,1), "bpb", "bpb", 'b', smallBattery, 'p', "plateCopper"). setRegistryName(new ResourceLocation("advancedrocketry", "itemBattery11"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), "ppp", " g ", " l ", 'p', Blocks.GLASS_PANE, 'g', Items.GLOWSTONE_DUST, 'l', "plateGold"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellitePrimaryFunction"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockObservatory), "gug", " b ", "rrr", 'g', "paneGlass", 'u', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'r', "stickIron"). setRegistryName(new ResourceLocation("advancedrocketry", "blockObservatory"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemThermite, 3), "dustAluminum", "dustIron","dustIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemThermite"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockThermiteTorch, 4), new ItemStack(Items.STICK), "dustThermite"). setRegistryName(new ResourceLocation("advancedrocketry", "blockThermiteTorch"))); // //Hatches toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,0), "m", "c"," ", 'c', AdvancedRocketryItems.itemDataUnit, 'm', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader10"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,1), " x ", "xmx"," x ", 'x', "stickTitanium", 'm', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader11"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,2), new ItemStack(LibVulpesBlocks.blockHatch,1,1), trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader12"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,3), new ItemStack(LibVulpesBlocks.blockHatch,1,0), trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader13"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,4), new ItemStack(LibVulpesBlocks.blockHatch,1,3), trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader14"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,5), new ItemStack(LibVulpesBlocks.blockHatch,1,2), trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader15"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLoader,1,6), " z ", "xmx"," z ", 'z' , controlCircuitBoard, 'x', "stickCopper", 'm', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockLoader16"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), "rrr", "ggg","ppp", 'r', "dustRedstone", 'g', Items.GLOWSTONE_DUST, 'p', "plateGold"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellitePowerSource"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(LibVulpesItems.itemHoloProjector), "oro", "rpr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'r', "dustRedstone", 'p', "plateIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemHoloProjector"))); toRegister.add(new ShapedOreRecipe(null, massDetector, "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', "crystalDilithium"). setRegistryName(new ResourceLocation("advancedrocketry", "massDetector"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellitePrimaryFunction11"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemLens, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellitePrimaryFunction13"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0), " x ","xox", " x ", 'x', "plateIron", 'o', "stickIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSawBlade"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockSawBlade,1,0), "r r","xox", "x x", 'r', "stickIron", 'x', "plateIron", 'o', new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0)). setRegistryName(new ResourceLocation("advancedrocketry", "blockSawBlade"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSpaceStationChip), LibVulpesItems.itemLinker , basicCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "itemSpaceStationChip"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge), "xix", "xix", "xix", 'x', "sheetIron", 'i', Blocks.IRON_BARS). setRegistryName(new ResourceLocation("advancedrocketry", "itemCarbonScrubberCartridge"))); // //O2 Support toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockOxygenVent), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', LibVulpesBlocks.blockMotor, 't', AdvancedRocketryBlocks.blockFuelTank). setRegistryName(new ResourceLocation("advancedrocketry", "blockOxygenVent"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockOxygenScrubber), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', LibVulpesBlocks.blockMotor, 't', "ingotCarbon"). setRegistryName(new ResourceLocation("advancedrocketry", "blockOxygenScrubber"))); // //Knicknacks toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockForceFieldProjector), " c ", "pdp","psp", 'c', "coilCopper", 'p', "plateAluminum", 'd', "crystalDilithium", 's', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockForceFieldProjector"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockPipeSealer, " c ", "csc", " c ", 'c', Items.CLAY_BALL, 's', "stickIron"). setRegistryName(new ResourceLocation("advancedrocketry", "blockPipeSealer"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockAlienPlanks, 4), AdvancedRocketryBlocks.blockAlienWood). setRegistryName(new ResourceLocation("advancedrocketry", "blockAlienPlanks"))); // if(zmaster587.advancedRocketry.api.Configuration.enableGravityController) toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockGravityMachine), "sds", "sws", 's', "sheetTitanium", 'd', massDetector, 'w', AdvancedRocketryBlocks.blockWarpCore). setRegistryName(new ResourceLocation("advancedrocketry", "blockGravityMachine"))); // //MACHINES toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockPrecisionAssembler), "abc", "def", "ghi", 'a', Items.REPEATER, 'b', userInterface, 'c', "gemDiamond", 'd', itemIOBoard, 'e', LibVulpesBlocks.blockStructureBlock, 'f', controlCircuitBoard, 'g', Blocks.FURNACE, 'h', "gearSteel", 'i', Blocks.DROPPER). setRegistryName(new ResourceLocation("advancedrocketry", "blockPrecisionAssembler"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockCrystallizer), "ada", "ecf","bgb", 'a', Items.QUARTZ, 'b', Items.REPEATER, 'c', LibVulpesBlocks.blockStructureBlock, 'd', userInterface, 'e', itemIOBoard, 'f', controlCircuitBoard, 'g', "plateSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "blockCrystallizer"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockCuttingMachine), "aba", "cde", "opo", 'a', "gearSteel", 'b', userInterface, 'c', itemIOBoard, 'e', controlCircuitBoard, 'p', "plateSteel", 'o', Blocks.OBSIDIAN, 'd', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockCuttingMachine"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLathe), "rsr", "abc", "pgp", 'r', "stickIron",'a', itemIOBoard, 'c', controlCircuitBoard, 'g', "gearSteel", 'p', "plateSteel", 'b', LibVulpesBlocks.blockStructureBlock, 's', userInterface). setRegistryName(new ResourceLocation("advancedrocketry", "blockLathe"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockRollingMachine), "psp", "abc", "iti", 'a', itemIOBoard, 'c', controlCircuitBoard, 'p', "gearSteel", 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'i', "blockIron",'t', liquidIOBoard). setRegistryName(new ResourceLocation("advancedrocketry", "blockRollingMachine"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockMonitoringStation), "coc", "cbc", "cpc", 'c', "stickCopper", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'b', LibVulpesBlocks.blockStructureBlock, 'p', LibVulpesItems.itemBattery). setRegistryName(new ResourceLocation("advancedrocketry", "blockMonitoringStation"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockFuelingStation), "bgb", "lbf", "ppp", 'p', "plateTin", 'f', "fanSteel", 'l', liquidIOBoard, 'g', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockFuelingStation"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockSatelliteControlCenter), "oso", "cbc", "rtr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 's', userInterface, 'c', "stickCopper", 'b', LibVulpesBlocks.blockStructureBlock, 'r', Items.REPEATER, 't', LibVulpesItems.itemBattery). setRegistryName(new ResourceLocation("advancedrocketry", "blockSatelliteControlCenter"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockSatelliteBuilder), "dht", "cbc", "mas", 'd', AdvancedRocketryItems.itemDataUnit, 'h', Blocks.HOPPER, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'm', LibVulpesBlocks.blockMotor, 'a', Blocks.ANVIL, 's', AdvancedRocketryBlocks.blockSawBlade, 't', "plateTitanium"). setRegistryName(new ResourceLocation("advancedrocketry", "blockSatelliteBuilder"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockPlanetAnalyser), "tst", "pbp", "cpc", 't', trackingCircuit, 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateTin", 'c', AdvancedRocketryItems.itemPlanetIdChip). setRegistryName(new ResourceLocation("advancedrocketry", "blockPlanetAnalyser"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockGuidanceComputer), "ctc", "rbr", "crc", 'c', trackingCircuit, 't', "plateTitanium", 'r', "dustRedstone", 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockGuidanceComputer"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockPlanetSelector), "cpc", "lbl", "coc", 'c', trackingCircuit, 'o',new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'l', Blocks.LEVER, 'b', AdvancedRocketryBlocks.blockGuidanceComputer, 'p', Blocks.STONE_BUTTON). setRegistryName(new ResourceLocation("advancedrocketry", "blockPlanetSelector"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder), "sgs", "cbc", "tdt", 's', "stickTitanium", 'g', AdvancedRocketryItems.itemMisc, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 't', "gearTitanium", 'd', AdvancedRocketryBlocks.blockConcrete). setRegistryName(new ResourceLocation("advancedrocketry", "blockRocketBuilder"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockStationBuilder), "gdg", "dsd", "ada", 'g', "gearTitanium", 'a', advancedCircuit, 'd', "dustDilithium", 's', new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder)). setRegistryName(new ResourceLocation("advancedrocketry", "blockStationBuilder"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockElectrolyser), "pip", "abc", "ded", 'd', basicCircuit, 'p', "plateSteel", 'i', userInterface, 'a', liquidIOBoard, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'e', Blocks.REDSTONE_TORCH). setRegistryName(new ResourceLocation("advancedrocketry", "blockElectrolyser"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockOxygenCharger), "fif", "tbt", "pcp", 'p', "plateSteel", 'f', "fanSteel", 'c', Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE, 'i', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock, 't', AdvancedRocketryBlocks.blockFuelTank). setRegistryName(new ResourceLocation("advancedrocketry", "blockOxygenCharger"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockChemicalReactor), "pip", "abd", "rcr", 'a', itemIOBoard, 'd', controlCircuitBoard, 'r', basicCircuit, 'p', "plateGold", 'i', userInterface, 'c', liquidIOBoard, 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockChemicalReactor"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockWarpCore), "gcg", "pbp", "gcg", 'p', "plateSteel", 'c', advancedCircuit, 'b', "coilCopper", 'g', "plateTitanium"). setRegistryName(new ResourceLocation("advancedrocketry", "blockWarpCore"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockOxygenDetection), "pip", "gbf", "pcp", 'p', "plateSteel",'f', "fanSteel", 'i', userInterface, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'g', Blocks.IRON_BARS). setRegistryName(new ResourceLocation("advancedrocketry", "blockOxygenDetection"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockWarpShipMonitor), "pip", "obo", "pcp", 'o', controlCircuitBoard, 'p', "plateSteel", 'i', userInterface, 'c', advancedCircuit, 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockWarpShipMonitor"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockBiomeScanner), "plp", "bsb","ppp", 'p', "plateTin", 'l', biomeChanger, 'b', smallBattery, 's', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockBiomeScanner"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockDeployableRocketBuilder), "gdg", "dad", "rdr", 'g', "gearTitaniumAluminide", 'd', "dustDilithium", 'r', "stickTitaniumAluminide", 'a', AdvancedRocketryBlocks.blockRocketBuilder). setRegistryName(new ResourceLocation("advancedrocketry", "blockDeployableRocketBuilder"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockPressureTank), "tgt","tgt","tgt", 't', superHighPressureTime, 'g', Blocks.GLASS_PANE). setRegistryName(new ResourceLocation("advancedrocketry", "blockPressureTank"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockIntake), "rhr", "hbh", "rhr", 'r', "stickTitanium", 'h', Blocks.HOPPER, 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockIntake"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockRailgun), " t ", "abc", "ded", 't', trackingCircuit, 'a', controlCircuitBoard, 'b', LibVulpesBlocks.blockAdvStructureBlock, 'c', itemIOBoard, 'd', "fanSteel", 'e', "coilCopper"). setRegistryName(new ResourceLocation("advancedrocketry", "blockRailgun"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockSpaceElevatorController), " d ", "aba", "ccc", 'd', controlCircuitBoard, 'a', advancedCircuit, 'b', LibVulpesBlocks.blockAdvStructureBlock, 'c', "coilAluminum"). setRegistryName(new ResourceLocation("advancedrocketry", "blockSpaceElevatorController"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockBeacon), " c ", "dbt", "scs", 'c', "coilCopper", 'd', controlCircuitBoard, 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 's', "sheetIron" ). setRegistryName(new ResourceLocation("advancedrocketry", "blockBeacon"))); // //Armor recipes toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemSpaceSuit_Boots, " r ", "w w", "p p", 'r', "stickIron", 'w', Blocks.WOOL, 'p', "plateIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSpaceSuit_Boots"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemSpaceSuit_Leggings, "wrw", "w w", "w w", 'w', Blocks.WOOL, 'r', "stickIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSpaceSuit_Leggings"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemSpaceSuit_Chest, "wrw", "wtw", "wfw", 'w', Blocks.WOOL, 'r', "stickIron", 't', AdvancedRocketryBlocks.blockFuelTank, 'f', "fanSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSpaceSuit_Chest"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemSpaceSuit_Helmet, "prp", "rgr", "www", 'w', Blocks.WOOL, 'r', "stickIron", 'p', "plateIron", 'g', Blocks.GLASS_PANE). setRegistryName(new ResourceLocation("advancedrocketry", "itemSpaceSuit_Helmet"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemJetpack, "cpc", "lsl", "f f", 'c', AdvancedRocketryItems.itemPressureTank, 'f', Items.FIRE_CHARGE, 's', Items.STRING, 'l', Blocks.LEVER, 'p', "plateSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "itemJetpack"))); // //Tool Recipes toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemJackhammer, " pt","imp","di ",'d', "gemDiamond", 'm', LibVulpesBlocks.blockMotor, 'p', "plateAluminum", 't', "stickTitanium", 'i', "stickIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemJackhammer"))); // //Other blocks toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemSmallAirlockDoor, "pp", "pp","pp", 'p', "plateSteel"). setRegistryName(new ResourceLocation("advancedrocketry", "itemSmallAirlockDoor"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockCircleLight), "p ", " l ", " ", 'p', "sheetIron", 'l', Blocks.GLOWSTONE). setRegistryName(new ResourceLocation("advancedrocketry", "blockCircleLight"))); // //TEMP RECIPES toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0)). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatelliteIdChip"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemPlanetIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip)). setRegistryName(new ResourceLocation("advancedrocketry", "itemPlanetIdChip"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemMisc,1,1), charcoal, charcoal, charcoal, charcoal ,charcoal ,charcoal). setRegistryName(new ResourceLocation("advancedrocketry", "itemMisc11"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockLandingPad), new ItemStack(AdvancedRocketryBlocks.blockConcrete), trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockLandingPad"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemAsteroidChip), trackingCircuit.copy(), AdvancedRocketryItems.itemDataUnit). setRegistryName(new ResourceLocation("advancedrocketry", "itemAsteroidChip"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockDataPipe, 8), "ggg", " d ", "ggg", 'g', Blocks.GLASS_PANE, 'd', AdvancedRocketryItems.itemDataUnit). setRegistryName(new ResourceLocation("advancedrocketry", "blockDataPipe"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockEnergyPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "stickCopper"). setRegistryName(new ResourceLocation("advancedrocketry", "blockEnergyPipe"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockFluidPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "sheetCopper"). setRegistryName(new ResourceLocation("advancedrocketry", "blockFluidPipe"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockDrill), LibVulpesBlocks.blockStructureBlock, Items.IRON_PICKAXE). setRegistryName(new ResourceLocation("advancedrocketry", "blockDrill"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockOrientationController), LibVulpesBlocks.blockStructureBlock, Items.COMPASS, userInterface). setRegistryName(new ResourceLocation("advancedrocketry", "blockOrientationController"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockGravityController), LibVulpesBlocks.blockStructureBlock, Blocks.PISTON, Blocks.REDSTONE_BLOCK). setRegistryName(new ResourceLocation("advancedrocketry", "blockGravityController"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockAltitudeController), LibVulpesBlocks.blockStructureBlock, userInterface, basicCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "blockAltitudeController"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemLens), " g ", "g g", 'g', Blocks.GLASS_PANE). setRegistryName(new ResourceLocation("advancedrocketry", "itemLens"))); toRegister.add(new ShapelessOreRecipe(null, largeSolarPanel.copy(), smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel). setRegistryName(new ResourceLocation("advancedrocketry", "largeSolarPanel"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockMicrowaveReciever), "ggg", "tbc", "aoa", 'g', "plateGold", 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'c', controlCircuitBoard, 'a', advancedCircuit, 'o', opticalSensor). setRegistryName(new ResourceLocation("advancedrocketry", "blockMicrowaveReciever"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockSolarPanel, "rrr", "gbg", "ppp", 'r' , "dustRedstone", 'g', Items.GLOWSTONE_DUST, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateGold"). setRegistryName(new ResourceLocation("advancedrocketry", "blockSolarPanel"))); toRegister.add(new ShapelessOreRecipe(null, AdvancedRocketryBlocks.blockSolarGenerator, "itemBattery", LibVulpesBlocks.blockForgeOutputPlug, AdvancedRocketryBlocks.blockSolarPanel). setRegistryName(new ResourceLocation("advancedrocketry", "blockSolarGenerator"))); toRegister.add(new ShapelessOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockDockingPort), trackingCircuit, new ItemStack(AdvancedRocketryBlocks.blockLoader, 1,1)). setRegistryName(new ResourceLocation("advancedrocketry", "blockDockingPort"))); toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryItems.itemOreScanner, "lwl", "bgb", " ", 'l', Blocks.LEVER, 'g', userInterface, 'b', "itemBattery", 'w', advancedCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "itemOreScanner"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), " c ","sss", "tot", 'c', "stickCopper", 's', "sheetIron", 'o', AdvancedRocketryItems.itemOreScanner, 't', trackingCircuit). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellitePrimaryFunction14"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockSuitWorkStation), "c","b", 'c', Blocks.CRAFTING_TABLE, 'b', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockSuitWorkStation"))); toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryItems.itemSatellite), "sss", "rcr", "sss", 's', "sheetAluminum", 'r', "stickTitanium", 'c', controlCircuitBoard). setRegistryName(new ResourceLocation("advancedrocketry", "itemSatellite"))); // if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { toRegister.add(new ShapedOreRecipe(null, AdvancedRocketryBlocks.blockSpaceLaser, "ata", "bec", "gpg", 'a', advancedCircuit, 't', trackingCircuit, 'b', LibVulpesItems.itemBattery, 'e', Items.EMERALD, 'c', controlCircuitBoard, 'g', "gearTitanium", 'p', LibVulpesBlocks.blockStructureBlock). setRegistryName(new ResourceLocation("advancedrocketry", "blockSpaceLaser"))); // if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming) { toRegister.add(new ShapedOreRecipe(null, new ItemStack(AdvancedRocketryBlocks.blockAtmosphereTerraformer), "gdg", "lac", "gbg", 'g', "gearTitaniumAluminide", 'd', "crystalDilithium", 'l', liquidIOBoard, 'a', LibVulpesBlocks.blockAdvStructureBlock, 'c', controlCircuitBoard, 'b', battery2x). setRegistryName(new ResourceLocation("advancedrocketry", "blockAtmosphereTerraformer"))); // //Control boards toRegister.add(new ShapedOreRecipe(null, itemIOBoard, "rvr", "dwd", "dpd", 'r', "dustRedstone", 'v', "gemDiamond", 'd', "dustGold", 'w', "slabWood", 'p', "plateIron"). setRegistryName(new ResourceLocation("advancedrocketry", "itemIOBoard"))); toRegister.add(new ShapedOreRecipe(null, controlCircuitBoard, "rvr", "dwd", "dpd", 'r', "dustRedstone", 'v', "gemDiamond", 'd', "dustCopper", 'w', "slabWood", 'p', "plateIron"). setRegistryName(new ResourceLocation("advancedrocketry", "controlCircuitBoard"))); toRegister.add(new ShapedOreRecipe(null, liquidIOBoard, "rvr", "dwd", "dpd", 'r', "dustRedstone", 'v', "gemDiamond", 'd', new ItemStack(Items.DYE, 1, 4), 'w', "slabWood", 'p', "plateIron"). setRegistryName(new ResourceLocation("advancedrocketry", "liquidIOBoard"))); //OreDict stuff OreDictionary.registerOre("waferSilicon", new ItemStack(AdvancedRocketryItems.itemWafer,1,0)); OreDictionary.registerOre("ingotCarbon", new ItemStack(AdvancedRocketryItems.itemMisc, 1, 1)); OreDictionary.registerOre("concrete", new ItemStack(AdvancedRocketryBlocks.blockConcrete)); OreDictionary.registerOre("itemLens", AdvancedRocketryItems.itemLens); OreDictionary.registerOre("itemSilicon", MaterialRegistry.getItemStackFromMaterialAndType("Silicon", AllowedProducts.getProductByName("INGOT"))); OreDictionary.registerOre("dustThermite", new ItemStack(AdvancedRocketryItems.itemThermite)); for(net.minecraft.item.crafting.IRecipe recipe: toRegister) { GameData.register_impl(recipe); } //Register machines machineRecipes.registerMachine(TileElectrolyser.class); machineRecipes.registerMachine(TileCuttingMachine.class); machineRecipes.registerMachine(TileLathe.class); machineRecipes.registerMachine(TilePrecisionAssembler.class); machineRecipes.registerMachine(TileElectricArcFurnace.class); machineRecipes.registerMachine(TileChemicalReactor.class); machineRecipes.registerMachine(TileRollingMachine.class); machineRecipes.registerMachine(TileCrystallizer.class); //Register the machine recipes machineRecipes.registerAllMachineRecipes(); } @EventHandler public void load(FMLInitializationEvent event) { //TODO: move to proxy //Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler((IBlockColor) AdvancedRocketryBlocks.blockFuelFluid, new Block[] {AdvancedRocketryBlocks.blockFuelFluid}); proxy.init(); zmaster587.advancedRocketry.cable.NetworkRegistry.registerFluidNetwork(); //Register Alloys MaterialRegistry.registerMixedMaterial(new MixedMaterial(TileElectricArcFurnace.class, "oreRutile", new ItemStack[] {MaterialRegistry.getMaterialFromName("Titanium").getProduct(AllowedProducts.getProductByName("INGOT"))})); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); NetworkRegistry.INSTANCE.registerGuiHandler(this, new zmaster587.advancedRocketry.inventory.GuiHandler()); planetWorldType = new WorldTypePlanetGen("PlanetCold"); spaceWorldType = new WorldTypeSpace("Space"); String[] biomeBlackList = config.getStringList("BlacklistedBiomes", "Planet", new String[] {"7", "8", "9", "127", String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest))}, "List of Biomes to be blacklisted from spawning as BiomeIds, default is: river, sky, hell, void, alienForest"); String[] biomeHighPressure = config.getStringList("HighPressureBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.stormLandsBiome)) }, "Biomes that only spawn on worlds with pressures over 125, will override blacklist. Defaults: StormLands, DeepSwamp"); String[] biomeSingle = config.getStringList("SingleBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.crystalChasms)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest)), String.valueOf(Biome.getIdForBiome(Biomes.DESERT_HILLS)), String.valueOf(Biome.getIdForBiome(Biomes.MUSHROOM_ISLAND)), String.valueOf(Biome.getIdForBiome(Biomes.EXTREME_HILLS)), String.valueOf(Biome.getIdForBiome(Biomes.ICE_PLAINS)) }, "Some worlds have a chance of spawning single biomes contained in this list. Defaults: deepSwamp, crystalChasms, alienForest, desert hills, mushroom island, extreme hills, ice plains"); config.save(); //Prevent these biomes from spawning normally AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.spaceBiome); //Read BlackList from config and register Blacklisted biomes for(String string : biomeBlackList) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error blackListing biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerBlackListBiome(biome); } catch (NumberFormatException e) { logger.warn("Error blackListing \"" + string + "\". It is not a valid number"); } } if(zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes) { AdvancedRocketryBiomes.instance.blackListVanillaBiomes(); } //Read and Register High Pressure biomes from config for(String string : biomeHighPressure) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error registering high pressure biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerHighPressureBiome(biome); } catch (NumberFormatException e) { logger.warn("Error registering high pressure biome \"" + string + "\". It is not a valid number"); } } //Read and Register Single biomes from config for(String string : biomeSingle) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error registering single biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerSingleBiome(biome); } catch (NumberFormatException e) { logger.warn("Error registering single biome \"" + string + "\". It is not a valid number"); } } //Data mapping 'D' List<BlockMeta> list = new LinkedList<BlockMeta>(); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 0)); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 8)); TileMultiBlock.addMapping('D', list); machineRecipes.createAutoGennedRecipes(modProducts); } @EventHandler public void postInit(FMLPostInitializationEvent event) { CapabilitySpaceArmor.register(); //Need to raise the Max Entity Radius to allow player interaction with rockets World.MAX_ENTITY_RADIUS = 20; //Register multiblock items with the projector ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCuttingMachine(), (BlockTile)AdvancedRocketryBlocks.blockCuttingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileLathe(), (BlockTile)AdvancedRocketryBlocks.blockLathe); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCrystallizer(), (BlockTile)AdvancedRocketryBlocks.blockCrystallizer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePrecisionAssembler(), (BlockTile)AdvancedRocketryBlocks.blockPrecisionAssembler); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileObservatory(), (BlockTile)AdvancedRocketryBlocks.blockObservatory); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAstrobodyDataProcessor(), (BlockTile)AdvancedRocketryBlocks.blockPlanetAnalyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRollingMachine(), (BlockTile)AdvancedRocketryBlocks.blockRollingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectricArcFurnace(), (BlockTile)AdvancedRocketryBlocks.blockArcFurnace); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectrolyser(), (BlockTile)AdvancedRocketryBlocks.blockElectrolyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileChemicalReactor(), (BlockTile)AdvancedRocketryBlocks.blockChemicalReactor); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileWarpCore(), (BlockTile)AdvancedRocketryBlocks.blockWarpCore); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileMicrowaveReciever(), (BlockTile)AdvancedRocketryBlocks.blockMicrowaveReciever); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBiomeScanner(), (BlockTile)AdvancedRocketryBlocks.blockBiomeScanner); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAtmosphereTerraformer(), (BlockTile)AdvancedRocketryBlocks.blockAtmosphereTerraformer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRailgun(), (BlockTile)AdvancedRocketryBlocks.blockRailgun); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileSpaceElevator(), (BlockTile)AdvancedRocketryBlocks.blockSpaceElevatorController); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBeacon(), (BlockTile)AdvancedRocketryBlocks.blockBeacon); if(zmaster587.advancedRocketry.api.Configuration.enableGravityController) ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileGravityController(), (BlockTile)AdvancedRocketryBlocks.blockGravityMachine); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileSpaceLaser(), (BlockTile)AdvancedRocketryBlocks.blockSpaceLaser); proxy.registerEventHandlers(); proxy.registerKeyBindings(); //TODO advancments // ARAchivements.register(); //TODO: debug //ClientCommandHandler.instance.registerCommand(new Debugger()); PlanetEventHandler handle = new PlanetEventHandler(); MinecraftForge.EVENT_BUS.register(handle); MinecraftForge.ORE_GEN_BUS.register(handle); //MinecraftForge.EVENT_BUS.register(new BucketHandler()); CableTickHandler cable = new CableTickHandler(); MinecraftForge.EVENT_BUS.register(cable); InputSyncHandler inputSync = new InputSyncHandler(); MinecraftForge.EVENT_BUS.register(inputSync); MinecraftForge.EVENT_BUS.register(new MapGenLander()); AdvancedRocketryAPI.gravityManager = new GravityHandler(); /*if(Loader.isModLoaded("GalacticraftCore") && zmaster587.advancedRocketry.api.Configuration.overrideGCAir) { GalacticCraftHandler eventHandler = new GalacticCraftHandler(); MinecraftForge.EVENT_BUS.register(eventHandler); if(event.getSide().isClient()) FMLCommonHandler.instance().bus().register(eventHandler); }*/ MinecraftForge.EVENT_BUS.register(SpaceObjectManager.getSpaceManager()); PacketHandler.init(); GameRegistry.registerWorldGenerator(new OreGenerator(), 100); ForgeChunkManager.setForcedChunkLoadingCallback(instance, new WorldEvents()); //Register buckets BucketHandler.INSTANCE.registerBucket(AdvancedRocketryBlocks.blockFuelFluid, AdvancedRocketryItems.itemBucketRocketFuel); //FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidRocketFuel, new ItemStack(AdvancedRocketryItems.itemBucketRocketFuel), new ItemStack(Items.BUCKET)); //FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidNitrogen, new ItemStack(AdvancedRocketryItems.itemBucketNitrogen), new ItemStack(Items.BUCKET)); //FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidHydrogen, new ItemStack(AdvancedRocketryItems.itemBucketHydrogen), new ItemStack(Items.BUCKET)); //FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidOxygen, new ItemStack(AdvancedRocketryItems.itemBucketOxygen), new ItemStack(Items.BUCKET)); //Register mixed material's recipes for(MixedMaterial material : MaterialRegistry.getMixedMaterialList()) { RecipesMachine.getInstance().addRecipe(material.getMachine(), material.getProducts(), 100, 10, material.getInput()); } //Register space dimension net.minecraftforge.common.DimensionManager.registerDimension(zmaster587.advancedRocketry.api.Configuration.spaceDimId, DimensionManager.spaceDimensionType); //Register fuels logger.info("Start registering liquid rocket fuels"); for(String str : liquidRocketFuel) { Fluid fluid = FluidRegistry.getFluid(str); if(fluid != null) { logger.info("Registering fluid "+ str + " as rocket fuel"); FuelRegistry.instance.registerFuel(FuelType.LIQUID, fluid, 1f); } else logger.warn("Fluid name" + str + " is not a registered fluid!"); } logger.info("Finished registering liquid rocket fuels"); liquidRocketFuel = null; //clean up //Register Whitelisted Sealable Blocks logger.info("Start registering sealable blocks"); for(String str : sealableBlockWhiteList) { Block block = Block.getBlockFromName(str); if(block == null) logger.warn("'" + str + "' is not a valid Block"); else SealableBlockHandler.INSTANCE.addSealableBlock(block); } logger.info("End registering sealable blocks"); sealableBlockWhiteList = null; logger.info("Start registering torch blocks"); for(String str : breakableTorches) { Block block = Block.getBlockFromName(str); if(block == null) logger.warn("'" + str + "' is not a valid Block"); else zmaster587.advancedRocketry.api.Configuration.torchBlocks.add(block); } logger.info("End registering torch blocks"); breakableTorches = null; logger.info("Start registering Harvestable Gasses"); for(String str : harvestableGasses) { Fluid fluid = FluidRegistry.getFluid(str); if(fluid == null) logger.warn("'" + str + "' is not a valid Fluid"); else AtmosphereRegister.getInstance().registerHarvestableFluid(fluid); } logger.info("End registering Harvestable Gasses"); harvestableGasses = null; logger.info("Start registering entity atmosphere bypass"); //Add armor stand by default zmaster587.advancedRocketry.api.Configuration.bypassEntity.add(EntityArmorStand.class); for(String str : entityList) { Class clazz = (Class) EntityList.getClass(new ResourceLocation(str)); //If not using string name maybe it's a class name? if(clazz == null) { try { clazz = Class.forName(str); if(clazz != null && !Entity.class.isAssignableFrom(clazz)) clazz = null; } catch (Exception e) { //Fail silently } } if(clazz != null) { logger.info("Registering " + clazz.getName() + " for atmosphere bypass"); zmaster587.advancedRocketry.api.Configuration.bypassEntity.add(clazz); } else logger.warn("Cannot find " + str + " while registering entity for atmosphere bypass"); } //Free memory entityList = null; logger.info("End registering entity atmosphere bypass"); //Register geodeOres if(!zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList) { for(String str : geodeOres) zmaster587.advancedRocketry.api.Configuration.standardGeodeOres.add(str); } //Register laserDrill ores if(!zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList) { for(String str : orbitalLaserOres) zmaster587.advancedRocketry.api.Configuration.standardLaserDrillOres.add(str); } //Do blacklist stuff for ore registration for(String oreName : OreDictionary.getOreNames()) { if(zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList && oreName.startsWith("ore")) { boolean found = false; for(String str : geodeOres) { if(oreName.equals(str)) { found = true; break; } } if(!found) zmaster587.advancedRocketry.api.Configuration.standardGeodeOres.add(oreName); } if(zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList && oreName.startsWith("ore")) { boolean found = false; for(String str : orbitalLaserOres) { if(oreName.equals(str)) { found = true; break; } } if(!found) zmaster587.advancedRocketry.api.Configuration.standardLaserDrillOres.add(oreName); } } //TODO recipes? machineRecipes.registerXMLRecipes(); //Add the overworld as a discovered planet zmaster587.advancedRocketry.api.Configuration.initiallyKnownPlanets.add(0); } @EventHandler public void serverStarted(FMLServerStartedEvent event) { for (int dimId : DimensionManager.getInstance().getLoadedDimensions()) { DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(dimId); if(!properties.isNativeDimension && properties.getId() == zmaster587.advancedRocketry.api.Configuration.MoonId && !Loader.isModLoaded("GalacticraftCore")) { properties.isNativeDimension = true; } } } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new WorldCommand()); int dimOffset = DimensionManager.dimOffset; //Open ore files //Load Asteroids from XML File file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/asteroidConfig.xml"); logger.info("Checking for asteroid config at " + file.getAbsolutePath()); if(!file.exists()) { logger.info(file.getAbsolutePath() + " not found, generating"); try { file.createNewFile(); BufferedWriter stream; stream = new BufferedWriter(new FileWriter(file)); stream.write("<Asteroids>\n\t<asteroid name=\"Small Asteroid\" distance=\"10\" mass=\"100\" massVariability=\"0.5\" minLevel=\"0\" probability=\"10\" richness=\"0.2\" richnessVariability=\"0.5\">" + "\n\t\t<ore itemStack=\"minecraft:iron_ore\" chance=\"15\" />" + "\n\t\t<ore itemStack=\"minecraft:gold_ore\" chance=\"10\" />" + "\n\t\t<ore itemStack=\"minecraft:redstone_ore\" chance=\"10\" />" + "\n\t</asteroid>" + "\n\t<asteroid name=\"Iridium Enriched asteroid\" distance=\"100\" mass=\"25\" massVariability=\"0.5\" minLevel=\"0\" probability=\"0.75\" richness=\"0.2\" richnessVariability=\"0.3\">" + "\n\t\t<ore itemStack=\"minecraft:iron_ore\" chance=\"25\" />" + "\n\t\t<ore itemStack=\"libvulpes:ore0 10\" chance=\"5\" />" + "\n\t</asteroid>" + "\n</Asteroids>"); stream.close(); } catch (IOException e) { e.printStackTrace(); } } XMLAsteroidLoader load = new XMLAsteroidLoader(); try { load.loadFile(file); for(AsteroidSmall asteroid : load.loadPropertyFile()) { zmaster587.advancedRocketry.api.Configuration.asteroidTypes.put(asteroid.ID, asteroid); } } catch (IOException e) { e.printStackTrace(); } // End load asteroids from XML file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/oreConfig.xml"); logger.info("Checking for ore config at " + file.getAbsolutePath()); if(!file.exists()) { logger.info(file.getAbsolutePath() + " not found, generating"); try { file.createNewFile(); BufferedWriter stream; stream = new BufferedWriter(new FileWriter(file)); stream.write("<OreConfig>\n</OreConfig>"); stream.close(); } catch (IOException e) { e.printStackTrace(); } } else { XMLOreLoader oreLoader = new XMLOreLoader(); try { oreLoader.loadFile(file); List<SingleEntry<HashedBlockPosition, OreGenProperties>> mapping = oreLoader.loadPropertyFile(); for(Entry<HashedBlockPosition, OreGenProperties> entry : mapping) { int pressure = entry.getKey().x; int temp = entry.getKey().y; if(pressure == -1) { if(temp != -1) { OreGenProperties.setOresForTemperature(Temps.values()[temp], entry.getValue()); } } else if(temp == -1) { if(pressure != -1) { OreGenProperties.setOresForPressure(AtmosphereTypes.values()[pressure], entry.getValue()); } } else { OreGenProperties.setOresForPressureAndTemp(AtmosphereTypes.values()[pressure], Temps.values()[temp], entry.getValue()); } } } catch (IOException e) { e.printStackTrace(); } } //End open and load ore files //Load planet files //Note: loading this modifies dimOffset DimensionPropertyCoupling dimCouplingList = null; XMLPlanetLoader loader = null; boolean loadedFromXML = false; //Check advRocketry folder first File localFile; localFile = file = new File(net.minecraftforge.common.DimensionManager.getCurrentSaveRootDirectory() + "/" + DimensionManager.workingPath + "/planetDefs.xml"); logger.info("Checking for config at " + file.getAbsolutePath()); if(!file.exists()) { //Hi, I'm if check #42, I am true if the config is not in the world/advRocketry folder file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/planetDefs.xml"); logger.info("File not found. Now checking for config at " + file.getAbsolutePath()); //Copy file to local dir if(file.exists()) { logger.info("Advanced Planet Config file Found! Copying to world specific directory"); try { File dir = new File(localFile.getAbsolutePath().substring(0, localFile.getAbsolutePath().length() - localFile.getName().length())); //File cannot exist due to if check if((dir.exists() || dir.mkdir()) && localFile.createNewFile()) { char buffer[] = new char[1024]; FileReader reader = new FileReader(file); FileWriter writer = new FileWriter(localFile); int numChars = 0; while((numChars = reader.read(buffer)) > 0) { writer.write(buffer, 0, numChars); } reader.close(); writer.close(); logger.info("Copy success!"); } else logger.warn("Unable to create file " + localFile.getAbsolutePath()); } catch(IOException e) { logger.warn("Unable to write file " + localFile.getAbsolutePath()); } } } if(file.exists()) { logger.info("Advanced Planet Config file Found! Loading from file."); loader = new XMLPlanetLoader(); try { loader.loadFile(file); dimCouplingList = loader.readAllPlanets(); DimensionManager.dimOffset += dimCouplingList.dims.size(); } catch(IOException e) { } } //End load planet files //Register hard coded dimensions if(!zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().loadDimensions(zmaster587.advancedRocketry.dimension.DimensionManager.workingPath)) { int numRandomGeneratedPlanets = 9; int numRandomGeneratedGasGiants = 1; if(dimCouplingList != null) { logger.info("Loading initial planet config!"); for(StellarBody star : dimCouplingList.stars) { DimensionManager.getInstance().addStar(star); } for(DimensionProperties properties : dimCouplingList.dims) { DimensionManager.getInstance().registerDimNoUpdate(properties, properties.isNativeDimension); properties.setStar(properties.getStarId()); } for(StellarBody star : dimCouplingList.stars) { numRandomGeneratedPlanets = loader.getMaxNumPlanets(star); numRandomGeneratedGasGiants = loader.getMaxNumGasGiants(star); dimCouplingList.dims.addAll(generateRandomPlanets(star, numRandomGeneratedPlanets, numRandomGeneratedGasGiants)); } loadedFromXML = true; } if(!loadedFromXML) { //Make Sol StellarBody sol = new StellarBody(); sol.setTemperature(100); sol.setId(0); sol.setName("Sol"); DimensionManager.getInstance().addStar(sol); //Add the overworld DimensionManager.getInstance().registerDimNoUpdate(DimensionManager.overworldProperties, false); sol.addPlanet(DimensionManager.overworldProperties); if(zmaster587.advancedRocketry.api.Configuration.MoonId == -1) zmaster587.advancedRocketry.api.Configuration.MoonId = DimensionManager.getInstance().getNextFreeDim(dimOffset); //Register the moon if(zmaster587.advancedRocketry.api.Configuration.MoonId != -1) { DimensionProperties dimensionProperties = new DimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId); dimensionProperties.setAtmosphereDensityDirect(0); dimensionProperties.averageTemperature = 20; dimensionProperties.rotationalPeriod = 128000; dimensionProperties.gravitationalMultiplier = .166f; //Actual moon value dimensionProperties.setName("Luna"); dimensionProperties.orbitalDist = 150; dimensionProperties.addBiome(AdvancedRocketryBiomes.moonBiome); dimensionProperties.setParentPlanet(DimensionManager.overworldProperties); dimensionProperties.setStar(DimensionManager.getSol()); dimensionProperties.isNativeDimension = !Loader.isModLoaded("GalacticraftCore"); DimensionManager.getInstance().registerDimNoUpdate(dimensionProperties, !Loader.isModLoaded("GalacticraftCore")); } generateRandomPlanets(DimensionManager.getSol(), numRandomGeneratedPlanets, numRandomGeneratedGasGiants); StellarBody star = new StellarBody(); star.setTemperature(10); star.setPosX(300); star.setPosZ(-200); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Wolf 12"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 5, 0); star = new StellarBody(); star.setTemperature(170); star.setPosX(-200); star.setPosZ(80); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Epsilon ire"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 7, 0); star = new StellarBody(); star.setTemperature(200); star.setPosX(-150); star.setPosZ(250); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Proxima Centaurs"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 3, 0); star = new StellarBody(); star.setTemperature(70); star.setPosX(-150); star.setPosZ(-250); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Magnis Vulpes"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 2, 0); } } else { VersionCompat.upgradeDimensionManagerPostLoad(DimensionManager.prevBuild); } //Clean up floating stations and satellites if(resetFromXml) { //Move all space stations to the overworld for(ISpaceObject obj : SpaceObjectManager.getSpaceManager().getSpaceObjects()) { if(obj.getOrbitingPlanetId() != 0 ) { SpaceObjectManager.getSpaceManager().moveStationToBody(obj, 0, false); } } //Satellites are cleaned up on their own as dimension properties are reset } //Attempt to load ore config from adv planet XML if(dimCouplingList != null) { //Register new stars for(StellarBody star : dimCouplingList.stars) { if(DimensionManager.getInstance().getStar(star.getId()) == null) DimensionManager.getInstance().addStar(star); DimensionManager.getInstance().getStar(star.getId()).subStars = star.subStars; } for(DimensionProperties properties : dimCouplingList.dims) { //Register dimensions loaded by other mods if not already loaded if(!properties.isNativeDimension && properties.getStar() != null && !DimensionManager.getInstance().isDimensionCreated(properties.getId())) { for(StellarBody star : dimCouplingList.stars) { for(StellarBody loadedStar : DimensionManager.getInstance().getStars()) { if(star.getId() == properties.getStarId() && star.getName().equals(loadedStar.getName())) { DimensionManager.getInstance().registerDimNoUpdate(properties, false); properties.setStar(loadedStar); } } } } //Overwrite with loaded XML if(DimensionManager.getInstance().isDimensionCreated(properties.getId())) { DimensionProperties loadedProps = DimensionManager.getInstance().getDimensionProperties(properties.getId()); loadedProps.fogColor = properties.fogColor; loadedProps.gravitationalMultiplier = properties.gravitationalMultiplier; loadedProps.hasRings = properties.hasRings; loadedProps.orbitalDist = properties.getOrbitalDist(); loadedProps.ringColor = properties.ringColor; loadedProps.orbitalPhi = properties.orbitalPhi; loadedProps.rotationalPeriod = properties.rotationalPeriod; loadedProps.skyColor = properties.skyColor; loadedProps.setBiomeEntries(properties.getBiomes()); loadedProps.setAtmosphereDensityDirect(properties.getAtmosphereDensity()); loadedProps.setName(properties.getName()); if(properties.isGasGiant()) loadedProps.setGasGiant(); //Register gasses if needed if(!properties.getHarvestableGasses().isEmpty() && properties.getHarvestableGasses() != loadedProps.getHarvestableGasses()) { loadedProps.getHarvestableGasses().clear(); loadedProps.getHarvestableGasses().addAll(properties.getHarvestableGasses()); } if(!loadedProps.isMoon() && properties.isMoon()) loadedProps.setParentPlanet(properties.getParentProperties()); if(loadedProps.isMoon() && !properties.isMoon()) { loadedProps.getParentProperties().removeChild(loadedProps.getId()); loadedProps.setParentPlanet(null); } } else { DimensionManager.getInstance().registerDim(properties, properties.isNativeDimension); } if(!properties.customIcon.isEmpty()) { DimensionProperties loadedProps; if(DimensionManager.getInstance().isDimensionCreated(properties.getId())) { loadedProps = DimensionManager.getInstance().getDimensionProperties(properties.getId()); loadedProps.customIcon = properties.customIcon; } } //TODO: add properties fromXML //Add artifacts if needed if(DimensionManager.getInstance().isDimensionCreated(properties.getId())) { DimensionProperties loadedProps; loadedProps = DimensionManager.getInstance().getDimensionProperties(properties.getId()); List<ItemStack> list = new LinkedList<ItemStack>(properties.getRequiredArtifacts()); loadedProps.getRequiredArtifacts().clear(); loadedProps.getRequiredArtifacts().addAll(list); } if(properties.oreProperties != null) { DimensionProperties loadedProps = DimensionManager.getInstance().getDimensionProperties(properties.getId()); if(loadedProps != null) loadedProps.oreProperties = properties.oreProperties; } } //Remove dimensions not in the XML for(int i : DimensionManager.getInstance().getRegisteredDimensions()) { boolean found = false; for(DimensionProperties properties : dimCouplingList.dims) { if(properties.getId() == i) { found = true; break; } } if(!found) { DimensionManager.getInstance().deleteDimension(i); } } //Remove stars not in the XML for(int i : new HashSet<Integer>(DimensionManager.getInstance().getStarIds())) { boolean found = false; for(StellarBody properties : dimCouplingList.stars) { if(properties.getId() == i) { found = true; break; } } if(!found) { DimensionManager.getInstance().removeStar(i); } } //Add planets for(StellarBody star : dimCouplingList.stars) { int numRandomGeneratedPlanets = loader.getMaxNumPlanets(star); int numRandomGeneratedGasGiants = loader.getMaxNumGasGiants(star); generateRandomPlanets(star, numRandomGeneratedPlanets, numRandomGeneratedGasGiants); } } // make sure to set dim offset back to original to make things consistant DimensionManager.dimOffset = dimOffset; DimensionManager.getInstance().knownPlanets.addAll(zmaster587.advancedRocketry.api.Configuration.initiallyKnownPlanets); } private List<DimensionProperties> generateRandomPlanets(StellarBody star, int numRandomGeneratedPlanets, int numRandomGeneratedGasGiants) { List<DimensionProperties> dimPropList = new LinkedList<DimensionProperties>(); Random random = new Random(System.currentTimeMillis()); for(int i = 0; i < numRandomGeneratedGasGiants; i++) { int baseAtm = 180; int baseDistance = 100; DimensionProperties properties = DimensionManager.getInstance().generateRandomGasGiant(star.getId(), "",baseDistance + 50,baseAtm,125,100,100,75); dimPropList.add(properties); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(8); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); if(moonProperties == null) continue; dimPropList.add(moonProperties); moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } for(int i = 0; i < numRandomGeneratedPlanets; i++) { int baseAtm = 75; int baseDistance = 100; if(i % 4 == 0) { baseAtm = 0; } else if(i != 6 && (i+2) % 4 == 0) baseAtm = 120; if(i % 3 == 0) { baseDistance = 170; } else if((i + 1) % 3 == 0) { baseDistance = 30; } DimensionProperties properties = DimensionManager.getInstance().generateRandom(star.getId(), baseDistance,baseAtm,125,100,100,75); if(properties == null) continue; dimPropList.add(properties); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(4); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); if(moonProperties == null) continue; dimPropList.add(moonProperties); moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } return dimPropList; } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); zmaster587.advancedRocketry.cable.NetworkRegistry.clearNetworks(); SpaceObjectManager.getSpaceManager().onServerStopped(); zmaster587.advancedRocketry.api.Configuration.MoonId = -1; DimensionManager.getInstance().overworldProperties.resetProperties(); ((BlockSeal)AdvancedRocketryBlocks.blockPipeSealer).clearMap(); DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 8000, "Dimensions including and after this number are allowed to be made into planets"); DimensionManager.getInstance().knownPlanets.clear(); if(!zmaster587.advancedRocketry.api.Configuration.lockUI) proxy.saveUILayout(config); } @SubscribeEvent public void registerOre(OreRegisterEvent event) { //Register ore products if(!zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) return; for(AllowedProducts product : AllowedProducts.getAllAllowedProducts() ) { if(event.getName().startsWith(product.name().toLowerCase(Locale.ENGLISH))) { HashSet<String> list = modProducts.get(product); if(list == null) { list = new HashSet<String>(); modProducts.put(product, list); } list.add(event.getName().substring(product.name().length())); } } //GT uses stick instead of Rod if(event.getName().startsWith("rod")) { HashSet<String> list = modProducts.get(AllowedProducts.getProductByName("STICK")); if(list == null) { list = new HashSet<String>(); modProducts.put(AllowedProducts.getProductByName("STICK"), list); } list.add(event.getName().substring("rod".length())); } } }
package roart.model; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // dummy //import net.sf.ehcache.hibernate.EhCacheRegionFactory; public class HibernateUtil { private static Logger log = LoggerFactory.getLogger(HibernateUtil.class); private static SessionFactory factory = null; private static Session session = null; private static Transaction transaction = null; public static Session getCurrentSession() throws /*MappingException,*/ HibernateException, Exception { return getHibernateSession(); } public static Session currentSession() throws /*MappingException,*/ HibernateException, Exception { return getHibernateSession(); } public static Session getHibernateSession() throws /*MappingException,*/ HibernateException, Exception { if (factory == null) { /* AnnotationConfiguration configuration = new AnnotationConfiguration(); factory = configuration.configure().buildSessionFactory();*/ /* Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(). applySettings(configuration.getProperties()); factory = configuration.buildSessionFactory(builder.build()); */ Configuration configuration = new Configuration().configure(); String connectionUrl = System.getProperty("connection.url"); //System.out.println("olds" + configuration.getProperties()); //System.out.println("curl " + connectionUrl); if (connectionUrl != null) { configuration.setProperty("connection.url", connectionUrl); configuration.setProperty("hibernate.connection.url", connectionUrl); } //System.out.println("news" + configuration.getProperties()); factory = configuration.buildSessionFactory(); //Object o = new net.sf.ehcache.hibernate.EhCacheRegionFactory(); } if (session == null) { //Session sess = factory.openSession(); session = factory.getCurrentSession(); } if (session != null) { if (!session.isOpen()) { session = factory.openSession(); } } if (transaction == null) { transaction = session.beginTransaction(); } return session; } public static Session getMyHibernateSession() throws /*MappingException,*/ HibernateException, Exception { if (factory == null) { /* AnnotationConfiguration configuration = new AnnotationConfiguration(); factory = configuration.configure().buildSessionFactory();*/ /* Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(). applySettings(configuration.getProperties()); factory = configuration.buildSessionFactory(builder.build()); */ Configuration configuration = new Configuration().configure(); String connectionUrl = System.getProperty("connection.url"); if (connectionUrl != null) { configuration.setProperty("connection.url", connectionUrl); configuration.setProperty("hibernate.connection.url", connectionUrl); } factory = configuration.buildSessionFactory(); //factory = new Configuration().configure().buildSessionFactory(); //Object o = new net.sf.ehcache.hibernate.EhCacheRegionFactory(); } if (session == null) { //Session sess = factory.openSession(); session = factory.getCurrentSession(); } if (session != null) { if (!session.isOpen()) { session = factory.openSession(); } } return session; } public static void commit() throws /*MappingException,*/ HibernateException, Exception { log.info("Doing hibernate commit"); if (transaction != null) { transaction.commit(); transaction = null; } if (session != null && session.isOpen()) { session.close(); session = null; } } public static <T> List<T> convert(List l, Class<T> type) { return (List<T>)l; } }
package com.bluedot.efactura.controllers; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.List; import java.util.Objects; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.bluedot.commons.controllers.AbstractController; import com.bluedot.commons.error.APIException; import com.bluedot.commons.error.APIException.APIErrors; import com.bluedot.commons.error.ErrorMessage; import com.bluedot.commons.security.Secured; import com.bluedot.commons.utils.ThreadMan; import com.bluedot.efactura.model.Empresa; import com.bluedot.efactura.model.FirmaDigital; import com.bluedot.efactura.serializers.EfacturaJSONSerializerProvider; import com.bluedot.efactura.services.ConsultaRutService; import com.bluedot.efactura.services.impl.ConsultaRutServiceImpl; import com.fasterxml.jackson.databind.JsonNode; import com.play4jpa.jpa.db.Tx; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import play.libs.F.Promise; import play.mvc.Result; import play.mvc.Security; @ErrorMessage @Tx @Security.Authenticated(Secured.class) @Api(value = "Operaciones de Empresa") public class EmpresasController extends AbstractController { final static Logger logger = LoggerFactory.getLogger(EmpresasController.class); // private Mutex mutex; // @Inject // public EmpresasController(Mutex mutex){ // this.mutex = mutex; public Promise<Result> darInformacionRut(String idrut) throws APIException { //TODO tomar este consulta rut de un factory ConsultaRutService service = new ConsultaRutServiceImpl(); // Call the service String response = service.getRutData(idrut); return json(response); } public Promise<Result> cargarEmpresas(String path) throws APIException { try { File fXmlFile = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); // optional, but recommended // read this - doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("RucEmisoresTransicionMail.RucEmisoresTransicionMailItem"); List<Empresa> empresas = Empresa.findAll(); HashMap<String, Empresa> empresasMap = new HashMap<String, Empresa>(); for (Empresa empresa : empresas) { empresasMap.put(empresa.getRut(), empresa); } for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String rut = eElement.getElementsByTagName("RUC").item(0).getTextContent(); logger.info("Procesando RUT: " + rut + " " + (temp + 1) + "/" + nList.getLength()); String denominacion = eElement.getElementsByTagName("DENOMINACION").item(0).getTextContent(); //String fechaInicio = eElement.getElementsByTagName("FECHA_INICIO").item(0).getTextContent(); String mail = eElement.getElementsByTagName("MAIL").item(0).getTextContent(); Empresa empresa = empresasMap.get(rut); if ( empresa == null) { empresa = new Empresa(rut, null, null, null, null, null); empresa.setEmisorElectronico(true); empresa.setMailRecepcion(mail); empresa.setRazon(denominacion); empresasMap.put(rut, empresa); empresa.save(); }else{ if (!empresa.isEmisorElectronico() || !Objects.equals(empresa.getMailRecepcion(), mail) || !Objects.equals(empresa.getRazon(), denominacion)) { empresa.setEmisorElectronico(true); empresa.setMailRecepcion(mail); empresa.setRazon(denominacion); empresa.update(); } } if (temp % 1000 == 0) ThreadMan.forceTransactionFlush(); } } } catch (Exception e) { e.printStackTrace(); } return json(OK); } public Promise<Result> getEmpresaById(int id) throws APIException { Empresa empresa = Empresa.findById(id, true); JSONObject json = EfacturaJSONSerializerProvider.getEmpresaSerializer().objectToJson(empresa); return json(json.toString()); } @ApiOperation(value = "Buscar Empresa por Rut", response = Empresa.class ) public Promise<Result> getEmpresaByRut(String rut) throws APIException { Empresa empresa = Empresa.findByRUT(rut, true); JSONObject json = EfacturaJSONSerializerProvider.getEmpresaSerializer().objectToJson(empresa); return json(json.toString()); } public Promise<Result> getEmpresas() throws APIException { List<Empresa> empresas = Empresa.findAll(); JSONArray json = EfacturaJSONSerializerProvider.getEmpresaSerializer().objectToJson(empresas); return json(json.toString()); } //TODO permisis de edicion public Promise<Result> editarEmpresa(String rut) throws APIException { Empresa empresa = Empresa.findByRUT(rut,true); JsonNode empresaJson = request().body().asJson(); String departamento = empresaJson.has("departamento") ? empresaJson.findPath("departamento").asText() : null; String direccion = empresaJson.has("direccion") ? empresaJson.findPath("direccion").asText() : null; String nombreComercial = empresaJson.has("nombreComercial") ? empresaJson.findPath("nombreComercial").asText() : null; String localidad = empresaJson.has("localidad") ? empresaJson.findPath("localidad").asText() : null; Integer codigoSucursal = empresaJson.has("codigoSucursal") ? empresaJson.findPath("codigoSucursal").asInt() : null; String logoPath = empresaJson.has("logoPath") ? empresaJson.findPath("logoPath").asText() : null; String paginaWeb = empresaJson.has("paginaWeb") ? empresaJson.findPath("paginaWeb").asText() : null; String telefono = empresaJson.has("telefono") ? empresaJson.findPath("telefono").asText() : null; String codigoPostal = empresaJson.has("codigoPostal") ? empresaJson.findPath("codigoPostal").asText() : null; String resolucion = empresaJson.has("resolucion") ? empresaJson.findPath("resolucion").asText() : null; String razon = empresaJson.has("razon") ? empresaJson.findPath("razon").asText() : null; String hostRecepcion = empresaJson.has("hostRecepcion") ? empresaJson.findPath("hostRecepcion").asText() : null; String passRecepcion = empresaJson.has("passRecepcion") ? empresaJson.findPath("passRecepcion").asText() : null; String puertoRecepcion = empresaJson.has("puertoRecepcion") ? empresaJson.findPath("puertoRecepcion").asText() : null; String userRecepcion = empresaJson.has("userRecepcion") ? empresaJson.findPath("userRecepcion").asText() : null; String mailNotificaciones = empresaJson.has("mailNotificaciones") ? empresaJson.findPath("mailNotificaciones").asText() : null; String fromEnvio = empresaJson.has("fromEnvio") ? empresaJson.findPath("fromEnvio").asText() : null; String certificado = empresaJson.has("certificado") ? empresaJson.findPath("certificado").asText() : null; String privateKey = empresaJson.has("privateKey") ? empresaJson.findPath("privateKey").asText() : null; if (hostRecepcion != null) empresa.setHostRecepcion(hostRecepcion); if (passRecepcion != null) empresa.setPassRecepcion(passRecepcion); if (puertoRecepcion != null) empresa.setPuertoRecepcion(puertoRecepcion); if (userRecepcion != null) empresa.setUserRecepcion(userRecepcion); if (mailNotificaciones != null) empresa.setMailNotificaciones(mailNotificaciones); if (fromEnvio != null) empresa.setFromEnvio(fromEnvio); if (paginaWeb != null) empresa.setPaginaWeb(paginaWeb); if (telefono != null) empresa.setTelefono(telefono); if (codigoPostal != null) empresa.setCodigoPostal(codigoPostal); if (codigoSucursal != null) empresa.setCodigoSucursal(codigoSucursal); if (departamento != null) empresa.setDepartamento(departamento); if (direccion != null) empresa.setDireccion(direccion); if (nombreComercial != null) empresa.setNombreComercial(nombreComercial); if (localidad != null) empresa.setLocalidad(localidad); if (resolucion != null) empresa.setResolucion(resolucion); if (razon != null) empresa.setRazon(razon); if (logoPath!=null){ Path path = Paths.get(logoPath); try { byte[] logo = Files.readAllBytes(path); empresa.setLogo(logo); } catch (IOException e) { } } if (certificado != null){ if (privateKey ==null) throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("privateKey").setDetailMessage("privateKey"); FirmaDigital firmaDigital = new FirmaDigital(); firmaDigital.setCertificate(certificado); firmaDigital.setPrivateKey(privateKey); try { KeyStore keystore = firmaDigital.getKeyStore(); if(keystore.getCertificate(FirmaDigital.KEY_ALIAS).getType().equals("X.509")){ X509Certificate certificate = (X509Certificate) keystore.getCertificate(FirmaDigital.KEY_ALIAS); firmaDigital.setValidaHasta(certificate.getNotAfter()); firmaDigital.setValidaDesde(certificate.getNotBefore()); if (empresa.getFirmaDigital()!=null) empresa.getFirmaDigital().delete(); firmaDigital.setEmpresa(empresa); firmaDigital.save(); } } catch (IOException | GeneralSecurityException e) { throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).setDetailMessage("certificado invalido o clave privada invalida"); } } empresa.update(); return json(OK); } }
package tabletop2; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import tabletop2.util.MyRigidBodyControl; import com.jme3.bounding.BoundingVolume; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.joints.SixDofJoint; import com.jme3.bullet.joints.SliderJoint; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; public class Table implements ActionListener { private static final Logger logger = Logger.getLogger(Table.class.getName()); private static Random random = new Random(5566); private String name; private boolean enabled = true; private Node rootNode; private Factory factory; private BulletAppState bulletAppState; private Inventory inventory; private Node robotLocationNode; private float tableWidth = 20; private float tableDepth = 12; private static final float TABLE_HEIGHT = 4; private Spatial tableSpatial = null; private int idSN = 0; private HashSet<String> uniqueIds = new HashSet<String>(); public Table(String name, MainApp app, Node robotLocationNode) { this.name = name; rootNode = app.getRootNode(); factory = app.getFactory(); bulletAppState = app.getBulletAppState(); inventory = app.getInventory(); this.robotLocationNode = robotLocationNode; } public float getWidth() { return tableWidth; } public float getDepth() { return tableDepth; } public ColorRGBA getColor() { return ColorRGBA.White; } public BoundingVolume getWorldBound() { return tableSpatial.getWorldBound(); } public void setEnabled(boolean v) { enabled = v; } public void reloadXml(String xmlFname) { // remove the table (if exists) if (tableSpatial != null) { MyRigidBodyControl rbc = tableSpatial.getControl(MyRigidBodyControl.class); if (rbc != null) { bulletAppState.getPhysicsSpace().remove(rbc); tableSpatial.removeControl(rbc); } rootNode.detachChild(tableSpatial); } // remove all free items (items not currently being grasped) inventory.removeAllFreeItems(); uniqueIds.clear(); for (Spatial s : inventory.allItems()) { uniqueIds.add(s.getName()); } idSN = 0; loadXml(xmlFname); // relocate the robot according to table size robotLocationNode.setLocalTransform(Transform.IDENTITY); robotLocationNode.setLocalTranslation(0, 2, tableDepth / 2 + 3); robotLocationNode.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y)); } private void loadXml(String xmlFname) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http: DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e1) { String msg = "parse error: " + xmlFname; logger.log(Level.WARNING, msg, e1); JOptionPane.showMessageDialog(null, msg + ": " + e1.getMessage()); makeTable(); return; } db.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); Document doc = null; try { doc = db.parse(new File(xmlFname)); } catch (SAXException e) { String msg = "cannot parse " + xmlFname; logger.log(Level.WARNING, msg, e); JOptionPane.showMessageDialog(null, msg + ": " + e.getMessage()); makeTable(); return; } catch (IOException e) { String msg = "cannot read from " + xmlFname; logger.log(Level.WARNING, msg, e); JOptionPane.showMessageDialog(null, msg + ": " + e.getMessage()); makeTable(); return; } catch (RuntimeException e) { String msg = "an error occurs in " + xmlFname; logger.log(Level.WARNING, msg, e); JOptionPane.showMessageDialog(null, msg + ": " + e.getMessage()); makeTable(); return; } Element docRoot = doc.getDocumentElement(); // get table size tableWidth = Float.parseFloat(docRoot.getAttribute("xspan")); tableDepth = Float.parseFloat(docRoot.getAttribute("yspan")); makeTable(); NodeList firstLevelNodeList = docRoot.getChildNodes(); for (int i = 0; i < firstLevelNodeList.getLength(); ++i) { org.w3c.dom.Node node = docRoot.getChildNodes().item(i); if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element elm = (Element) node; if (elm.getNodeName().equals("block")) { processBlockElement(elm, true); } else if (elm.getNodeName().equals("cylinder")) { processCylinderElement(elm, true); } else if (elm.getNodeName().equals("sphere")) { processSphereElement(elm, true); } else if (elm.getNodeName().equals("box")) { processBoxElement(elm, true); } else if (elm.getNodeName().equals("composite")) { processCompositeElement(elm, true); } else if (elm.getNodeName().equals("chain")) { processChainElement(elm); } else if (elm.getNodeName().equals("lidbox")) { processLidBoxElement(elm); } else if (elm.getNodeName().equals("dock")) { processDockElement(elm); } else if (elm.getNodeName().equals("cartridge")) { processCartridgeElement(elm); } else if (elm.getNodeName().equals("customShape")) { processCustomShapeElement(elm, true); } } } } private void makeTable() { // make table tableSpatial = factory.makeBigBlock(name, tableWidth, TABLE_HEIGHT, tableDepth, ColorRGBA.White, 4); tableSpatial.setLocalTranslation(0, -TABLE_HEIGHT / 2, 0); MyRigidBodyControl rbc = new MyRigidBodyControl(0); tableSpatial.addControl(rbc); bulletAppState.getPhysicsSpace().add(rbc); rootNode.attachChild(tableSpatial); } private Spatial processBlockElement(Element elm, boolean isWhole) { String id = elm.getAttribute("id"); if (isWhole) { id = getUniqueId(id); } Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); ColorRGBA color = parseColor(elm.getAttribute("color")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); Spatial s = factory.makeBlock(id, xspan, yspan, zspan, color); s.setLocalTranslation(location); s.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); if (isWhole) { float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(s, mass); } return s; } private Spatial processCylinderElement(Element elm, boolean isWhole) { String id = elm.getAttribute("id"); if (isWhole) { id = getUniqueId(id); } Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); ColorRGBA color = parseColor(elm.getAttribute("color")); float radius = Float.parseFloat(elm.getAttribute("radius")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); Spatial s = factory.makeCylinder(id, radius, zspan, color); s.setLocalTranslation(location); s.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); if (isWhole) { float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(s, mass); } return s; } private Spatial processSphereElement(Element elm, boolean isWhole) { String id = elm.getAttribute("id"); if (isWhole) { id = getUniqueId(id); } Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); ColorRGBA color = parseColor(elm.getAttribute("color")); float radius = Float.parseFloat(elm.getAttribute("radius")); Spatial s = factory.makeSphere(id, radius, color); s.setLocalTranslation(location); s.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); if (isWhole) { float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(s, mass); } return s; } private Spatial processBoxElement(Element elm, boolean isWhole) { String id = elm.getAttribute("id"); if (isWhole) { id = getUniqueId(id); } Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); ColorRGBA color = parseColor(elm.getAttribute("color")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); float thickness = Float.parseFloat(elm.getAttribute("thickness")); Spatial s = factory.makeBoxContainer(id, xspan, yspan, zspan, thickness, color); s.setLocalTranslation(location); s.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); if (isWhole) { float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(s, mass); } return s; } private Spatial processCompositeElement(Element elm, boolean isWhole) { String id = elm.getAttribute("id"); if (isWhole) { id = getUniqueId(id); } Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); Node node = new Node(id); node.setLocalTranslation(location); node.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); NodeList children = elm.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { if (children.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element child = (Element) children.item(i); if (child.getNodeName().equals("block")) { node.attachChild(processBlockElement(child, false)); } else if (child.getNodeName().equals("cylinder")) { node.attachChild(processCylinderElement(child, false)); } else if (child.getNodeName().equals("sphere")) { node.attachChild(processSphereElement(child, false)); } else if (child.getNodeName().equals("box")) { node.attachChild(processBoxElement(child, false)); } else if (child.getNodeName().equals("composite")) { node.attachChild(processCompositeElement(child, false)); } else if (child.getNodeName().equals("customShape")) { node.attachChild(processCustomShapeElement(child, false)); } } } // functional spots are discarded for non-top level if (isWhole) { float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(node, mass); node.setUserData("obj_shape", "composite"); // if (id.equals("screwdriver")) { // inventory.addFixedJoint(node, inventory.getItem("bolt0"), Vector3f.ZERO, Vector3f.ZERO); } return node; } private void processChainElement(Element elm) { String groupId = getUniqueId(elm.getAttribute("id")); ColorRGBA color = parseColor(elm.getAttribute("color")); Vector3f start = parseVector3(elm.getAttribute("start")); Vector3f end = parseVector3(elm.getAttribute("end")); float linkXspan = Float.parseFloat(elm.getAttribute("linkXspan")); float linkYspan = Float.parseFloat(elm.getAttribute("linkZspan")); float linkZspan = Float.parseFloat(elm.getAttribute("linkYspan")); int linkCount = Integer.parseInt(elm.getAttribute("linkCount")); float linkPadding = Float.parseFloat(elm.getAttribute("linkPadding")); float linkMass = Float.parseFloat(elm.getAttribute("linkMass")); // check if linkCount is enough to connect from start to end locations float dist = start.distance(end); if (linkCount == 0) { linkCount = (int) FastMath.ceil(dist / linkZspan); logger.log(Level.INFO, "chain " + groupId + ": linkCount=" + linkCount); } else { if ((float) linkCount * linkZspan < dist - linkZspan * .5f) { throw new IllegalArgumentException("linkCount " + linkCount + " too low to connect the start and end locations"); } } // start making a chain Vector3f vec = new Vector3f(); // temporary storage final Vector3f endNodesSize = new Vector3f(.1f, .1f, .1f); final Vector3f linkPhysicsSize = new Vector3f(linkXspan / 2, linkYspan / 2, linkZspan / 2); // rotate the z axis to the start->end direction // when walking on the links from start to end, z increases in each local model space Quaternion rotStartEndDir = new Quaternion(); rotStartEndDir.lookAt(start.subtract(end), Vector3f.UNIT_Y); // make start node (static) String id; id = getUniqueId(groupId + "-start"); Spatial startNode = factory.makeBlock(id, endNodesSize.x, endNodesSize.y, endNodesSize.z, ColorRGBA.White); startNode.setLocalTranslation(start); startNode.setLocalRotation(rotStartEndDir); inventory.addItem(startNode, 0); // make end node (static) id = getUniqueId(groupId + "-end"); Spatial endNode = factory.makeBlock(id, endNodesSize.x, endNodesSize.y, endNodesSize.z, ColorRGBA.White); endNode.setLocalTranslation(end); endNode.setLocalRotation(rotStartEndDir); inventory.addItem(endNode, 0); Spatial prevSpatial = startNode; Vector3f prevJointPt = new Vector3f(0, 0, -endNodesSize.z); for (int i = 0; i < linkCount; ++i) { // make a link id = getUniqueId(groupId + "-link" + i); Spatial link = factory.makeBlock(id, linkXspan, linkYspan, linkZspan + linkPadding * 2, color); link.setLocalRotation(rotStartEndDir); vec.interpolate(start, end, (i + .5f) / linkCount); link.setLocalTranslation(vec); inventory.addItem(link, linkMass, new BoxCollisionShape(linkPhysicsSize)); link.getControl(MyRigidBodyControl.class).setAngularDamping(1); // connect the link using a joint (or constraint) SixDofJoint joint = inventory.addSixDofJoint(prevSpatial, link, prevJointPt, new Vector3f(0, 0, linkZspan / 2)); joint.setCollisionBetweenLinkedBodys(false); prevSpatial = link; prevJointPt = new Vector3f(0, 0, -linkZspan / 2); } // connect the last link to the end node vec.set(0, 0, endNodesSize.z); inventory.addSixDofJoint(prevSpatial, endNode, prevJointPt, vec); } private void processLidBoxElement(Element elm) { String groupId = getUniqueId(elm.getAttribute("id")); Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); ColorRGBA color = parseColor(elm.getAttribute("color")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); float thickness = Float.parseFloat(elm.getAttribute("thickness")); ColorRGBA handleColor = parseColor(elm.getAttribute("handleColor")); float handleXspan = Float.parseFloat(elm.getAttribute("handleXspan")); float handleYspan = Float.parseFloat(elm.getAttribute("handleZspan")); float handleZspan = Float.parseFloat(elm.getAttribute("handleYspan")); float handleThickness = Float.parseFloat(elm.getAttribute("handleThickness")); Transform tf = new Transform(); tf.setTranslation(location); tf.setRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); String id; id = getUniqueId(groupId + "-box"); Spatial box = factory.makeBoxContainer(id, xspan, yspan, zspan, thickness, color); box.setLocalTransform(tf); float mass = Float.parseFloat(elm.getAttribute("mass")); inventory.addItem(box, mass); id = getUniqueId(groupId + "-lid"); Node lid = new Node(id); Spatial lidPlate = factory.makeBlock(id + "-lidbody", xspan, thickness, zspan, color); lid.attachChild(lidPlate); Spatial lidHandle = factory.makeBoxContainer(id + "-lidhandle", handleXspan, handleYspan, handleZspan, handleThickness, handleColor); lidHandle.setLocalTranslation(0, thickness / 2 + handleYspan / 2, 0); lid.attachChild(lidHandle); lid.setLocalTranslation(0, yspan / 2 + thickness / 2, 0); lid.setLocalTransform(lid.getLocalTransform().combineWithParent(tf)); float lidMass = Float.parseFloat(elm.getAttribute("lidMass")); inventory.addItem(lid, lidMass); lid.setUserData("obj_shape", "lid"); lid.setUserData("obj_width", lidPlate.getUserData("obj_width")); lid.setUserData("obj_height", lidPlate.getUserData("obj_height")); lid.setUserData("obj_depth", lidPlate.getUserData("obj_depth")); lid.setUserData("obj_handleWidth", lidHandle.getUserData("obj_width")); lid.setUserData("obj_handleHeight", lidHandle.getUserData("obj_height")); lid.setUserData("obj_handleDepth", lidHandle.getUserData("obj_depth")); lid.setUserData("obj_handleThickness", lidHandle.getUserData("obj_thickness")); inventory.addSliderJoint(box, lid, new Vector3f(0, yspan / 2, 0), new Vector3f(0, -thickness / 2, 0), 0, xspan); // joint.setCollisionBetweenLinkedBodys(false); // joint.setLowerLinLimit(0); // joint.setUpperLinLimit(xspan); // joint.setDampingDirLin(.001f); // joint.setRestitutionOrthoLin(.5f); // joint.setRestitutionDirLin(0); // joint.setPoweredLinMotor(true); // joint.setMaxLinMotorForce(1); // joint.setTargetLinMotorVelocity(-1); } private void processDockElement(Element elm) { final int NUM_MODULES = 4; String groupId = getUniqueId(elm.getAttribute("id")); Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); float xThickness = Float.parseFloat(elm.getAttribute("xthickness")); float yThickness = Float.parseFloat(elm.getAttribute("zthickness")); float zThickness = Float.parseFloat(elm.getAttribute("ythickness")); float handleXspan = Float.parseFloat(elm.getAttribute("handleXspan")); float handleYspan = Float.parseFloat(elm.getAttribute("handleZspan")); float handleZspan = Float.parseFloat(elm.getAttribute("handleYspan")); ColorRGBA color = parseColor(elm.getAttribute("color")); ColorRGBA caseColor = parseColor(elm.getAttribute("caseColor")); ColorRGBA handleColor = parseColor(elm.getAttribute("handleColor")); float mass = Float.parseFloat(elm.getAttribute("mass")); float caseMass = Float.parseFloat(elm.getAttribute("caseMass")); int[] switchStates = new int[NUM_MODULES]; int[] lightStates = new int[NUM_MODULES]; for (int i = 0; i < NUM_MODULES; ++i) { switchStates[i] = Integer.parseInt(elm.getAttribute("switchState" + (i + 1))); lightStates[i] = Integer.parseInt(elm.getAttribute("lightState" + (i + 1))); } Transform tf = new Transform(); tf.setTranslation(location); tf.setRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); String id; // case id = getUniqueId(groupId + "-case"); Spatial caseShape = factory.makeBoxContainer(id + "-shape", yspan, xspan - xThickness, zspan, yThickness, xThickness, zThickness, caseColor); caseShape.setLocalRotation(new Quaternion().fromAngleAxis(-FastMath.HALF_PI, Vector3f.UNIT_Z)); caseShape.setLocalTranslation(-xThickness / 2, 0, 0); Node caseNode = new Node(id); caseNode.setLocalTransform(tf); caseNode.attachChild(caseShape); inventory.addItem(caseNode, caseMass); caseNode.setUserData("obj_shape", "dock-case"); caseNode.setUserData("obj_width", caseShape.getUserData("obj_width")); caseNode.setUserData("obj_height", caseShape.getUserData("obj_height")); caseNode.setUserData("obj_depth", caseShape.getUserData("obj_depth")); caseNode.setUserData("obj_color", caseShape.getUserData("obj_color")); caseNode.setUserData("obj_xthickness", caseShape.getUserData("obj_xthickness")); caseNode.setUserData("obj_ythickness", caseShape.getUserData("obj_ythickness")); caseNode.setUserData("obj_zthickness", caseShape.getUserData("obj_zthickness")); // (component sizes and locations) float wBase = xspan - 2 * xThickness; float hPanel = 0.15f; float hBase = yspan - 2 * yThickness - 0.5f - hPanel; float dBase = zspan - 2 * zThickness; float thSlot = 0.087f; float wHole = 1.375f; float hHole = 0.648f; float dHole = 0.625f; float wHoleToPanel = 0.5f; float wPanel = wBase * 0.4048f; float wSwitch = 1.15f; float hSwitch = 0.05f; float dSwitch = 0.45f; float wPanelToSwitch = wBase * 0.0071f; float wSwitchToIndicator = wBase * 0.0119f; float rIndicator = dSwitch / 3; float hIndicator = hSwitch; // dock Node dockNode = new Node(groupId + "-body"); dockNode.setLocalTransform(tf); Node dockOffsetNode = new Node(groupId + "-bodyOffset"); dockOffsetNode.setLocalTranslation(0, -(yspan - yThickness * 2 - hBase) / 2, 0); dockNode.attachChild(dockOffsetNode); // dock base String baseId = getUniqueId(groupId + "-dock-base"); Node base = new Node(id); // dock base back id = getUniqueId(baseId + "-baseB"); float wBaseB = wBase - (wPanel + wHoleToPanel + wHole); Spatial baseB = factory.makeBlock(id, wBaseB, hBase, dBase, color); baseB.setLocalTranslation(-wBase / 2 + wBaseB / 2, 0, 0); base.attachChild(baseB); // dock base front id = getUniqueId(baseId + "-baseF"); float wBaseF = wPanel + wHoleToPanel; Spatial baseF = factory.makeBlock(id, wBaseF, hBase, dBase, color); baseF.setLocalTranslation(wBase / 2 - wBaseF / 2, 0, 0); base.attachChild(baseF); // dock base near wall id = getUniqueId(baseId + "-baseNW"); float dBaseNW = (dBase - dHole * 4) * 0.25f; Spatial baseNW = factory.makeBlock(id, wHole, hBase, dBaseNW, color); baseNW.setLocalTranslation(-wBase / 2 + wBaseB + wHole / 2, 0, -dBase / 2 + dBaseNW / 2); base.attachChild(baseNW); // dock base far wall id = getUniqueId(baseId + "-baseFW"); Spatial baseFW = factory.makeBlock(id, wHole, hBase, dBaseNW, color); baseFW.setLocalTranslation(-wBase / 2 + wBaseB + wHole / 2, 0, dBase / 2 - dBaseNW / 2); base.attachChild(baseFW); // dock base divider wall 1 id = getUniqueId(baseId + "-baseDW1"); float dBaseDW = (dBase - dHole * 4) * 0.5f / 3; Spatial baseDW1 = factory.makeBlock(id, wHole, hBase, dBaseDW, color); baseDW1.setLocalTranslation(-wBase / 2 + wBaseB + wHole / 2, 0, -dBase / 2 + dBaseNW + dHole + dBaseDW / 2); base.attachChild(baseDW1); // dock base divider wall 2 id = getUniqueId(baseId + "-baseDW2"); Spatial baseDW2 = factory.makeBlock(id, wHole, hBase, dBaseDW, color); baseDW2.setLocalTranslation(-wBase / 2 + wBaseB + wHole / 2, 0, -dBase / 2 + dBaseNW + dHole * 2 + dBaseDW + dBaseDW / 2); base.attachChild(baseDW2); // dock base divider wall 3 id = getUniqueId(baseId + "-baseDW3"); Spatial baseDW3 = factory.makeBlock(id, wHole, hBase, dBaseDW, color); baseDW3.setLocalTranslation(-wBase / 2 + wBaseB + wHole / 2, 0, -dBase / 2 + dBaseNW + dHole * 3 + dBaseDW * 2 + dBaseDW / 2); base.attachChild(baseDW3); // slots float slotX = -wBase / 2 + wBaseB + wHole / 2; float slotY = hBase / 2 - (hHole + 0.5f * thSlot) / 2; float[] slotZ = new float[NUM_MODULES]; for (int i = 0; i < NUM_MODULES; ++i) { id = getUniqueId(baseId + "-slot" + (i + 1)); Spatial slot = factory.makeBoxContainer(id, wHole, hHole + thSlot, dHole, thSlot, ColorRGBA.DarkGray); slotZ[i] = -dBase / 2 + dBaseNW + dHole / 2 + (dHole + dBaseDW) * i; slot.setLocalTranslation(slotX, slotY, slotZ[i]); base.attachChild(slot); id = getUniqueId(groupId + "-assemblyPoint" + (i + 1)); Node att = new Node(id); att.setLocalTranslation(slotX, slotY - hHole / 2, slotZ[i]); att.setLocalRotation(new Quaternion().fromAngles(-FastMath.HALF_PI, 0, 0)); att.setUserData("assembly", "cartridgeSlot"); att.setUserData("assemblyEnd", 0); base.attachChild(att); } // annotate... dockNode.setUserData("obj_shape", "dock-body"); dockNode.setUserData("obj_color", color); dockNode.setUserData("obj_width", xspan); dockNode.setUserData("obj_height", yspan); dockNode.setUserData("obj_depth", zspan); dockNode.setUserData("obj_baseWidth", wBase); dockNode.setUserData("obj_baseHeight", hBase); dockNode.setUserData("obj_baseDepth", dBase); dockNode.setUserData("obj_slotWidth", wHole - thSlot * 2); dockNode.setUserData("obj_slotHeight", hHole); dockNode.setUserData("obj_slotDepth", dHole - thSlot * 2); for (int i = 0; i < NUM_MODULES; ++i) { dockNode.setUserData("obj_slot" + (i + 1) + "OffsetX", slotX); dockNode.setUserData("obj_slot" + (i + 1) + "OffsetY", slotZ[i]); dockNode.setUserData("obj_slot" + (i + 1) + "OffsetZ", slotY); } // panel String panelId = getUniqueId(groupId + "-dock-panel"); Node panel = new Node(id); float panelX = wBase / 2 - wPanel / 2; float panelY = hBase / 2 + hPanel / 2; panel.setLocalTranslation(panelX, panelY, 0); // panel cover id = getUniqueId(panelId + "-panelCover"); Spatial panelCover = factory.makeBlock(id, wPanel, hPanel, dBase, color); panel.attachChild(panelCover); // switches Node[] switchButton = new Node[NUM_MODULES]; float switchX = -wPanel / 2 + wPanelToSwitch + wSwitch / 2; float switchY = hPanel / 2 + hSwitch / 2; for (int i = 0; i < NUM_MODULES; ++i) { id = getUniqueId(panelId + "-switch" + (i + 1)); Node switchNode = new Node(id); switchNode.setLocalTranslation(switchX, switchY, slotZ[i]); panel.attachChild(switchNode); // (base) id = getUniqueId(panelId + "-switch" + (i + 1) + "-base"); Spatial switchBase = factory.makeBlock(id, wSwitch, hSwitch, dSwitch, ColorRGBA.White); switchNode.attachChild(switchBase); // (button) switchButton[i] = new Node(groupId + "-switch" + (i + 1)); switchButton[i].setLocalTranslation(0, -0.1f, 0); Spatial b1 = factory.makeBlock("b1", 0.6f, 0.3f, 0.3f, ColorRGBA.DarkGray); b1.setLocalTranslation(-0.25f, 0, 0); b1.setLocalRotation(new Quaternion().fromAngles(0, 0, -3 * FastMath.DEG_TO_RAD)); Spatial b2 = factory.makeBlock("b2", 0.6f, 0.3f, 0.3f, ColorRGBA.DarkGray); b2.setLocalTranslation(0.25f, 0, 0); b2.setLocalRotation(new Quaternion().fromAngles(0, 0, 3 * FastMath.DEG_TO_RAD)); switchButton[i].attachChild(b1); switchButton[i].attachChild(b2); switchNode.attachChild(switchButton[i]); } // annotate... dockNode.setUserData("obj_switchWidth", 1.2f); dockNode.setUserData("obj_switchDepth", 0.3f); for (int i = 0; i < NUM_MODULES; ++i) { dockNode.setUserData("obj_switch" + (i + 1) + "OffsetX", panelX + switchX); dockNode.setUserData("obj_switch" + (i + 1) + "OffsetY", slotZ[i]); dockNode.setUserData("obj_switch" + (i + 1) + "OffsetZ", panelY + switchY); } // indicator lights Node[] indicatorLights = new Node[NUM_MODULES]; float lightX = -wPanel / 2 + wPanelToSwitch + wSwitch + wSwitchToIndicator + rIndicator; float lightY = hPanel / 2 + hIndicator / 2; for (int i = 0; i < NUM_MODULES; ++i) { id = getUniqueId(panelId + "-indicator" + (i + 1)); Node indicator = new Node(id); indicator.setLocalTranslation(lightX, lightY, slotZ[i]); panel.attachChild(indicator); // (base) id = getUniqueId(panelId + "-indicator" + (i + 1) + "-base"); Spatial indicatorBase = factory.makeCylinder(id, rIndicator, hIndicator, ColorRGBA.White); Quaternion rotX90 = new Quaternion().fromAngles(FastMath.HALF_PI, 0, 0); indicatorBase.setLocalRotation(rotX90); indicator.attachChild(indicatorBase); // (LEDs) id = getUniqueId(groupId + "-light" + (i + 1)); indicatorLights[i] = new Node(id); indicator.attachChild(indicatorLights[i]); // (green LED) Spatial greenLight = factory.makeCylinder("green", rIndicator / 5, 0.005f, ColorRGBA.Green); greenLight.setLocalTranslation(rIndicator / 2, hIndicator / 2 + 0.005f / 2, 0); greenLight.setLocalRotation(rotX90); indicatorLights[i].attachChild(greenLight); // (red LED) Spatial redLight = factory.makeCylinder("red", rIndicator / 5, 0.01f, ColorRGBA.Red); redLight.setLocalTranslation(-rIndicator / 2, hIndicator / 2 + 0.005f / 2, 0); redLight.setLocalRotation(rotX90); indicatorLights[i].attachChild(redLight); } // annotate... dockNode.setUserData("obj_lightRadius", rIndicator); for (int i = 0; i < NUM_MODULES; ++i) { dockNode.setUserData("obj_light" + (i + 1) + "OffsetX", panelX + lightX); dockNode.setUserData("obj_light" + (i + 1) + "OffsetY", slotZ[i]); dockNode.setUserData("obj_light" + (i + 1) + "OffsetZ", panelY + lightY); } dockOffsetNode.attachChild(base); dockOffsetNode.attachChild(panel); // dock front id = getUniqueId(groupId + "-dock-front"); Spatial front = factory.makeBlock(id, xThickness, yspan, zspan, color); front.setLocalTranslation(wBase / 2 + xThickness / 2, 0, 0); dockNode.attachChild(front); // dock handle id = getUniqueId(groupId + "-dock-handle"); Spatial handle = factory.makeBlock(id, handleXspan, handleYspan, handleZspan, handleColor); float handleY = yspan * 0.3583f; float handleX = wBase / 2 + xThickness + handleXspan / 2; handle.setLocalTranslation(handleX, handleY, 0); dockNode.attachChild(handle); dockNode.setUserData("obj_handleWidth", handleXspan); dockNode.setUserData("obj_handleHeight", handleYspan); dockNode.setUserData("obj_handleDepth", handleZspan); dockNode.setUserData("obj_handleOffsetX", handleX); dockNode.setUserData("obj_handleOffsetY", 0); dockNode.setUserData("obj_handleOffsetZ", handleY); dockNode.setUserData("obj_handleColor", handleColor); inventory.addItem(dockNode, mass); for (int i = 0; i < NUM_MODULES; ++i) { // LED function IndicatorLightFunction ilFunc = new IndicatorLightFunction(inventory, indicatorLights[i]); inventory.registerSpatialFunction(indicatorLights[i], ilFunc); // switch function SwitchFunction sFunc = new SwitchFunction(inventory, switchButton[i], ilFunc); inventory.registerSpatialFunction(switchButton[i], sFunc); // init states ilFunc.setState(lightStates[i]); sFunc.setState(switchStates[i]); } // sliding joint SliderJoint joint = inventory.addSliderJoint(dockNode, caseNode, Vector3f.ZERO, Vector3f.ZERO, 0, wBase); joint.setDampingDirLin(1); joint.setDampingDirAng(1); joint.setSoftnessOrthoLin(1); joint.setSoftnessOrthoAng(1); } private Spatial processCustomShapeElement(Element elm, boolean isWhole) { String id = getUniqueId(elm.getAttribute("id")); Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); float scale = Float.parseFloat(elm.getAttribute("scale")); ColorRGBA color = parseColor(elm.getAttribute("color")); String file = elm.getAttribute("file"); float mass = Float.parseFloat(elm.getAttribute("mass")); Spatial s = factory.makeCustom(id, file, xspan, yspan, zspan, color, scale); s.setLocalTranslation(location); s.setLocalScale(scale); s.updateModelBound(); s.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); if (isWhole) { inventory.addItem(s, mass); } return s; } private void processCartridgeElement(Element elm) { String groupId = getUniqueId(elm.getAttribute("id")); Vector3f location = parseVector3(elm.getAttribute("location")); Vector3f rotation = parseVector3(elm.getAttribute("rotation")); float xspan = Float.parseFloat(elm.getAttribute("xspan")); float yspan = Float.parseFloat(elm.getAttribute("zspan")); float zspan = Float.parseFloat(elm.getAttribute("yspan")); ColorRGBA bodyColor = parseColor(elm.getAttribute("color")); ColorRGBA handleColor = parseColor(elm.getAttribute("handleColor")); ColorRGBA topColor = parseColor(elm.getAttribute("topColor")); float mass = Float.parseFloat(elm.getAttribute("mass")); Node node = new Node(groupId); node.setLocalTranslation(location); node.setLocalRotation(new Quaternion().fromAngles( rotation.x * FastMath.DEG_TO_RAD, rotation.y * FastMath.DEG_TO_RAD, rotation.z * FastMath.DEG_TO_RAD)); String id; // body - central piece id = getUniqueId(groupId + "-bodyC"); float wBodyC = xspan * 3 / 7; float hBodyC = yspan; float dBodyC = zspan * 3 / 4; Spatial bodyC = factory.makeBlock(id, wBodyC, hBodyC, dBodyC, bodyColor); node.attachChild(bodyC); // body - left piece id = getUniqueId(groupId + "-bodyL"); float wBodyL = xspan * 2 / 7; float hBodyL = yspan; float dBodyL = zspan; // 0.8163f Spatial bodyL = factory.makeBlock(id, wBodyL, hBodyL, dBodyL, bodyColor); bodyL.setLocalTranslation(-(wBodyC / 2 + wBodyL / 2), 0, 0); node.attachChild(bodyL); // body - right piece id = getUniqueId(groupId + "-bodyR"); Spatial bodyR = factory.makeBlock(id, wBodyL, hBodyL, dBodyL, bodyColor); bodyR.setLocalTranslation(wBodyC / 2 + wBodyL / 2, 0, 0); node.attachChild(bodyR); // body - left foot id = getUniqueId(groupId + "-bodyLF"); float wBodyLF = xspan * 0.3116f; float hBodyLF = yspan * 0.1781f; float dBodyLF = zspan; Spatial bodyLF = factory.makeBlock(id, wBodyLF, hBodyLF, dBodyLF, bodyColor); bodyLF.setLocalTranslation(-(wBodyC / 2 + wBodyLF / 2), -(hBodyL / 2 + hBodyLF / 2), 0); node.attachChild(bodyLF); // body - right foot id = getUniqueId(groupId + "-bodyRF"); Spatial bodyRF = factory.makeBlock(id, wBodyLF, hBodyLF, dBodyLF, bodyColor); bodyRF.setLocalTranslation(wBodyC / 2 + wBodyLF / 2, -(hBodyL / 2 + hBodyLF / 2), 0); node.attachChild(bodyRF); // top id = getUniqueId(groupId + "-top"); float wTop = xspan * 1.1225f; float hTop = yspan * 0.1818f; float dTop = zspan * 1.225f; Spatial top = factory.makeBlock(id, wTop, hTop, dTop, topColor); top.setLocalTranslation(0, hBodyC / 2 + hTop / 2, 0); node.attachChild(top); // handle id = getUniqueId(groupId + "-top"); float wHandle = xspan * 0.7375f; float hHandle = yspan * 0.4545f; float dHandle = zspan * 0.695f; Spatial handle = factory.makeBlock(id, wHandle, hHandle, dHandle, handleColor); handle.setLocalTranslation(0, (hBodyC + hTop) / 2 + hHandle / 2, 0); node.attachChild(handle); // bottom attach point id = getUniqueId(groupId + "-assemblyPoint"); Node att = new Node(id); att.setLocalTranslation(0, -hBodyL / 2 - hBodyLF, 0); att.setLocalRotation(new Quaternion().fromAngles(FastMath.HALF_PI, 0, 0)); att.setUserData("assembly", "cartridgeSlot"); att.setUserData("assemblyEnd", 1); node.attachChild(att); // annotate... node.setUserData("obj_shape", "cartridge"); node.setUserData("obj_width", xspan); node.setUserData("obj_height", yspan); node.setUserData("obj_depth", zspan); node.setUserData("obj_color", bodyColor); node.setUserData("obj_handleColor", handleColor); node.setUserData("obj_topColor", topColor); inventory.addItem(node, mass); } private Vector3f parseVector3(String str) { Pattern pattern = Pattern.compile("^\\s*\\((\\-?\\d*(\\.\\d+)?)\\s*,\\s*(\\-?\\d*(\\.\\d+)?)\\s*,\\s*(\\-?\\d*(\\.\\d+)?)\\)\\s*$"); Matcher m = pattern.matcher(str); if (m.find()) { float x = Float.parseFloat(m.group(1)); float y = Float.parseFloat(m.group(5)); float z = -Float.parseFloat(m.group(3)); return new Vector3f(x, y, z); } throw new IllegalArgumentException("could not parse '" + str + "'"); } private ColorRGBA parseColor(String str) { if (str.equals("black")) { return ColorRGBA.Black; } else if (str.equals("blue")) { return ColorRGBA.Blue; } else if (str.equals("brown")) { return ColorRGBA.Brown; } else if (str.equals("cyan")) { return ColorRGBA.Cyan; } else if (str.equals("darkgray")) { return ColorRGBA.DarkGray; } else if (str.equals("gray")) { return ColorRGBA.Gray; } else if (str.equals("green")) { return ColorRGBA.Green; } else if (str.equals("lightgray")) { return ColorRGBA.LightGray; } else if (str.equals("magenta")) { return ColorRGBA.Magenta; } else if (str.equals("orange")) { return ColorRGBA.Orange; } else if (str.equals("pink")) { return ColorRGBA.Pink; } else if (str.equals("red")) { return ColorRGBA.Red; } else if (str.equals("white")) { return ColorRGBA.White; } else if (str.equals("yellow")) { return ColorRGBA.Yellow; } else { Pattern pattern = Pattern.compile("^\\s*#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})\\s*$"); Matcher m = pattern.matcher(str); if (m.find()) { int r = Integer.parseInt(m.group(1), 16); int g = Integer.parseInt(m.group(2), 16); int b = Integer.parseInt(m.group(3), 16); ColorRGBA color = new ColorRGBA(); color.fromIntRGBA((r << 24) + (g << 16) + (b << 8) + 0xff); return color; } throw new IllegalArgumentException("could not parse '" + str + "'"); } } public void dropRandomBlock() { final ColorRGBA[] colors = new ColorRGBA[] { ColorRGBA.Red, ColorRGBA.Blue, ColorRGBA.Yellow, ColorRGBA.Green, ColorRGBA.Brown, ColorRGBA.Cyan, ColorRGBA.Magenta, ColorRGBA.Orange }; Spatial s = factory.makeBlock(getUniqueId("largeblock"), 1.5f, 1.5f, 1.5f, colors[random.nextInt(colors.length)]); s.setLocalTranslation( (random.nextFloat() * 2 - 1) * (tableWidth / 2), 10, (random.nextFloat() * 2 - 1) * (tableDepth / 2)); s.setLocalRotation(new Quaternion().fromAngleAxis( FastMath.HALF_PI * random.nextFloat(), Vector3f.UNIT_XYZ)); inventory.addItem(s, 1); } public void dropRandomStackOfBlocks(int blockCount) { final Vector3f BOX_SIZE = new Vector3f(1, 1, 1); final ColorRGBA[] colors = new ColorRGBA[] { ColorRGBA.Red, ColorRGBA.Blue, ColorRGBA.Yellow, ColorRGBA.Green, ColorRGBA.Brown, ColorRGBA.Cyan, ColorRGBA.Magenta, ColorRGBA.Orange}; Vector3f pos = new Vector3f( (random.nextFloat() * 2 - 1) * (tableWidth / 2), BOX_SIZE.y / 2, (random.nextFloat() * 2 - 1) * (tableDepth / 2)); Quaternion rot = new Quaternion().fromAngleAxis( FastMath.HALF_PI * random.nextFloat(), Vector3f.UNIT_Y); for (int i = 0; i < blockCount; ++i) { Spatial s = factory.makeBlock(getUniqueId("smallblock"), BOX_SIZE.x, BOX_SIZE.y, BOX_SIZE.z, colors[random.nextInt(colors.length)]); s.setLocalTranslation(pos); s.setLocalRotation(rot); inventory.addItem(s, 1); pos.y += BOX_SIZE.y; } } public void dropRandomBoxContainer() { Spatial boxContainer = factory.makeBoxContainer(getUniqueId("container"), 5, 3, 5, 0.5f, ColorRGBA.Gray); boxContainer.setLocalTranslation((random.nextFloat() * 2 - 1) * (tableWidth / 2), 10, (random.nextFloat() * 2 - 1) * (tableDepth / 2)); boxContainer.setLocalRotation(new Quaternion().fromAngleAxis( FastMath.HALF_PI * random.nextFloat(), Vector3f.UNIT_XYZ)); inventory.addItem(boxContainer, 3); } private boolean isValidId(String id) { return id != null && !id.isEmpty() && !uniqueIds.contains(id); } private String getUniqueId(String prefix) { if (prefix == null || prefix.isEmpty()) { prefix = "obj"; } String id = prefix; while (!isValidId(id)) { id = prefix + "#" + (idSN++); } uniqueIds.add(id); return id; } public void initKeys(InputManager inputManager) { inputManager.addMapping(name + "MakeBlock", new KeyTrigger(KeyInput.KEY_B)); inputManager.addMapping(name + "MakeStack", new KeyTrigger(KeyInput.KEY_N)); inputManager.addMapping(name + "ClearTable", new KeyTrigger(KeyInput.KEY_C)); inputManager.addListener(this, name + "MakeBlock"); inputManager.addListener(this, name + "MakeStack"); inputManager.addListener(this, name + "ClearTable"); } @Override public void onAction(String eName, boolean isPressed, float tpf) { if (!enabled) { return; } if (eName.equals(name + "MakeBlock")) { if (!isPressed) { dropRandomBlock(); } } else if (eName.equals(name + "MakeStack")) { if (!isPressed) { dropRandomStackOfBlocks(5); } } else if (eName.equals(name + "ClearTable")) { if (!isPressed) { inventory.removeAllFreeItems(); } } } }
package com.jbooktrader.strategy; import com.jbooktrader.indicator.velocity.*; import com.jbooktrader.platform.indicator.*; import com.jbooktrader.platform.model.*; import com.jbooktrader.platform.optimizer.*; import com.jbooktrader.strategy.base.*; public class Defensive extends StrategyES { // Technical indicators private final Indicator balanceVelocityInd, trendStrengthVelocityInd; // Strategy parameters names private static final String FAST_PERIOD = "Fast Period"; private static final String SLOW_PERIOD = "Slow Period"; private static final String TREND_PERIOD = "Trend Period"; private static final String ENTRY = "Entry"; // Strategy parameters values private final int entry; public Defensive(StrategyParams optimizationParams) throws JBookTraderException { super(optimizationParams); entry = getParam(ENTRY); balanceVelocityInd = new BalanceVelocity(getParam(FAST_PERIOD), getParam(SLOW_PERIOD)); trendStrengthVelocityInd = new TrendStrengthVelocity(getParam(TREND_PERIOD)); addIndicator(balanceVelocityInd); addIndicator(trendStrengthVelocityInd); } /** * Adds parameters to strategy. Each parameter must have 5 values: * name: identifier * min, max, step: range for optimizer * value: used in backtesting and trading */ @Override public void setParams() { addParam(FAST_PERIOD, 1, 30, 1, 11); addParam(SLOW_PERIOD, 500, 5000, 100, 3485); addParam(TREND_PERIOD, 100, 900, 10, 611); addParam(ENTRY, 80, 220, 1, 165); } /** * This method is invoked by the framework when an order book changes and the technical * indicators are recalculated. This is where the strategy itself should be defined. */ @Override public void onBookChange() { double balanceVelocity = balanceVelocityInd.getValue() * 10; double trendStrengthVelocity = trendStrengthVelocityInd.getValue(); int currentPosition = getPositionManager().getPosition(); if (currentPosition > 0 && balanceVelocity <= -entry) { setPosition(0); } if (currentPosition < 0 && balanceVelocity >= entry) { setPosition(0); } if (trendStrengthVelocity < 0) { if (balanceVelocity >= entry) { setPosition(1); } else if (balanceVelocity <= -entry) { setPosition(-1); } } } }
package org.spoofax.jsglr; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.BufferedOutputStream; import java.io.OutputStream; public class Tools { private static OutputStream fos; private static String outfile = null; static { initOutput(); } public static void setOutput(String d) { outfile = d; initOutput(); } private static void initOutput() { if(fos == null) { try { if(outfile == null) outfile = ".jsglr-log"; fos = new BufferedOutputStream(new FileOutputStream(outfile)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } public static void debug(Object ...s) { // FIXME Copy debug() from org.spoofax.interpreter for(Object o : s) { System.err.print(o); } System.err.println(""); } public static void logger(Object ...s) { try { for(Object o : s) fos.write(o.toString().getBytes()); fos.write("\n".getBytes()); fos.flush(); } catch (IOException e) { e.printStackTrace(); } } static boolean debugging = false; static boolean logging = false; static boolean tracing = false; public static void setTracing(boolean enableTracing) { tracing = enableTracing; } public static void setDebug(boolean enableDebug) { debugging = enableDebug; } public static void setLogging(boolean enableLogging) { logging = enableLogging; setOutput(".jsglr-log"); } }
package qc; import csv.CSVLexer; import csv.CSVParser; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; import qc.QCMetrics.FreqProb; import qc.QCMetrics.QCMetric; import qc.RandomRespondent.AdversaryType; import scala.Tuple2; import survey.*; import survey.SurveyResponse.QuestionResponse; import system.mturk.MturkLibrary; /** * Entry point for quality control. * SurveyPoster functionality should be called in this class * */ public class QC { public enum QCActions { REJECT, BLOCK, APPROVE, DEQUALIFY; } public static final String BOT = "This worker has been determined to be a bot."; public static final String QUAL = "This worker has already taken one of our surveys."; public static final Random rng = new Random(System.currentTimeMillis()); public static final int bootstrapReps = 200; private Survey survey; private List<SurveyResponse> validResponses = new LinkedList<SurveyResponse>(); private List<SurveyResponse> botResponses = new LinkedList<SurveyResponse>(); public int numSyntheticBots = 0; public double alpha = 0.005; public QC(Survey survey) throws SurveyException { this.survey = survey; } /** * Finds outliers in the raw responses returned; uses parametric bootstrap for now. * @param responses * @return */ public List<SurveyResponse> getOutliers(List<SurveyResponse> responses, QCMetric metric, double alpha) { List<SurveyResponse> outliers = new ArrayList<SurveyResponse>(); List<Double> appliedStat = new ArrayList<Double>(); FreqProb fp = new FreqProb(survey, responses); for (SurveyResponse sr : responses) switch (metric) { case LIKELIHOOD: appliedStat.add(QCMetrics.getLogLikelihood(sr, fp)); break; } double[][] bootstrapSample = QCMetrics.makeBootstrapSample(appliedStat, bootstrapReps, rng); double[] bootstrapMeans = QCMetrics.getBootstrapMeans(bootstrapSample); //double[] bootstrapSEs = QCMetrics.getBootstrapSEs(bootstrapSample, bootstrapMeans); double bootstrapMean = QCMetrics.getBootstrapAvgMetric(bootstrapMeans); //double bootstrapSD = QCMetrics.getBootstrapSE(bootstrapSEs); double[] bootstrapUpperQuants = QCMetrics.getBootstrapUpperQuants(bootstrapSample, alpha); double[] bootstrapLowerQuants = QCMetrics.getBootstrapLowerQuants(bootstrapSample, alpha); double upperQuant = QCMetrics.getBootstrapAvgMetric(bootstrapUpperQuants); double lowerQuant = QCMetrics.getBootstrapAvgMetric(bootstrapLowerQuants); System.out.println(String.format("bootstrap mean : %f \t bootstrap upper %f : %f\t bootstrap lower %f : %f" , bootstrapMean, alpha, upperQuant, alpha, lowerQuant)); for (SurveyResponse sr : responses) { double likelihood = QCMetrics.getLogLikelihood(sr, fp); sr.score = likelihood; if (likelihood < lowerQuant || likelihood > upperQuant ) outliers.add(sr); else System.out.println(String.format("%s : %f", sr.srid, likelihood)); } return outliers; } private int getMaxM() { int m = 0; for (Question q : survey.questions) { int size = q.options.size(); if (size > m) m = size; } return m; } public List<RandomRespondent> makeBotPopulation (QCMetrics qcMetrics) throws SurveyException { List<RandomRespondent> syntheticBots = new ArrayList<RandomRespondent>(); int m = getMaxM(); double beta = 0.05; double delta = 0.1; // want our bot population to be large enough that every question has the expected number of bots with high prob int n = (int) Math.ceil((-3 * m * Math.log(beta)) / Math.pow(delta, 2)); numSyntheticBots = n; AdversaryType adversaryType = RandomRespondent.selectAdversaryProfile(qcMetrics); for (int i = 0 ; i < n ; i++) syntheticBots.add(new RandomRespondent(survey, adversaryType)); return syntheticBots; } public List<SurveyResponse> getSynthetic(List<SurveyResponse> responses, QCMetrics qcMetrics) throws SurveyException { List<RandomRespondent> syntheticBots = makeBotPopulation(qcMetrics); SurveyResponse[] allResponses = new SurveyResponse[responses.size() + syntheticBots.size()]; System.arraycopy(responses.toArray(new SurveyResponse[responses.size()]), 0, allResponses, 0, responses.size()); int i = responses.size(); for (RandomRespondent rr : syntheticBots){ allResponses[i] = rr.response; i++; } return getOutliers(Arrays.asList(allResponses), QCMetric.LIKELIHOOD, alpha); } public List<SurveyResponse> getBots(List<SurveyResponse> responses) throws SurveyException { Map<AdversaryType, Integer> adversaryTypeIntegerMap = new HashMap<AdversaryType, Integer>(); adversaryTypeIntegerMap.put(AdversaryType.UNIFORM, 1); return getSynthetic(responses, new QCMetrics(adversaryTypeIntegerMap)); } public List<SurveyResponse> getLazy(List<SurveyResponse> responses) throws SurveyException { Map<AdversaryType, Integer> adversaryTypeIntegerMap = new HashMap<AdversaryType, Integer>(); adversaryTypeIntegerMap.put(AdversaryType.FIRST, 1); adversaryTypeIntegerMap.put(AdversaryType.LAST, 1); return getSynthetic(responses, new QCMetrics(adversaryTypeIntegerMap)); } public List<SurveyResponse> getNoncommittal(List<SurveyResponse> responses) throws SurveyException { Map<AdversaryType, Integer> adversaryTypeIntegerMap = new HashMap<AdversaryType, Integer>(); adversaryTypeIntegerMap.put(AdversaryType.INNER, 1); return getSynthetic(responses, new QCMetrics(adversaryTypeIntegerMap)); } public boolean complete(List<SurveyResponse> responses, Properties props) { // this needs to be improved String numSamples = props.getProperty("numparticipants"); if (numSamples!=null) return validResponses.size() >= Integer.parseInt(numSamples); else return true; } /** * Assess the validity of the SurveyResponse {@link SurveyResponse}. * @param sr * @return A list of QCActions to be interpreted by the service's specification. */ public QCActions[] assess(SurveyResponse sr) { // add this survey response to the list of valid responses validResponses.add(sr); // update the frequency map to reflect this new response //updateFrequencyMap(); //updateAverageLikelihoods(); // classify this answer as a bot or not boolean bot = false; //isBot(sr); // classify any old responses as bot or not //updateValidResponses(); // recompute likelihoods //updateAverageLikelihoods(); if (bot) { return new QCActions[]{ QCActions.REJECT, QCActions.DEQUALIFY }; } else { //service.assignQualification("survey", a.getWorkerId(), 1, false); return new QCActions[]{ QCActions.APPROVE, QCActions.DEQUALIFY }; } } public static void main(String[] args) throws IOException, SurveyException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args.length < 2) System.out.println(String.format("USAGE:\t java -cp /path/to/jar qc.QC <survey_filename> <sep> <result_filename>")); String surveyFilename = args[0]; String sep = args[1]; String resultFilename = args[2]; CSVParser parser = new CSVParser(new CSVLexer(surveyFilename, sep)); Survey survey = parser.parse(); String qcFileName = String.format("%s%sqc_%s_%s.csv", MturkLibrary.OUTDIR, MturkLibrary.fileSep, survey.sourceName, MturkLibrary.TIME); QC qc = new QC(survey); List<SurveyResponse> responses = SurveyResponse.readSurveyResponses(survey, resultFilename); // take this out later List<Question> actualQuestionsAnswered = new LinkedList<Question>(); for (SurveyResponse sr : responses) { for (SurveyResponse.QuestionResponse qr : sr.responses) { boolean foundQ = false; for (Question q : actualQuestionsAnswered) if (q.quid.equals(qr.q.quid)){ foundQ = true; break; } if (!foundQ) actualQuestionsAnswered.add(qr.q); } } for (int i = 0 ; i < survey.questions.size() ; i++) { Question q = survey.questions.get(i); boolean foundQ = false; for (Question qq : actualQuestionsAnswered) if (qq.quid.equals(q.quid)) { foundQ = true; break; } if (!foundQ) survey.removeQuestion(q.quid); } // results to print List<SurveyResponse> outliers = qc.getOutliers(responses, QCMetric.LIKELIHOOD, qc.alpha); //List<SurveyResponse> lazy = qc.getLazy(responses); //List<SurveyResponse> boring = qc.getNoncommittal(responses); BufferedWriter bw = new BufferedWriter(new FileWriter(qcFileName)); bw.write(String.format("// %d OUTLIERS (out of %d obtained from mturk)%s", outliers.size(), responses.size(), SurveyResponse.newline)); for (SurveyResponse sr : outliers) bw.write(sr.srid + sep + sr.real + sep + sr.score + SurveyResponse.newline); List<SurveyResponse> bots = qc.getBots(responses); bw.write(String.format("// %d BOTS detected (out of %d synthesized) %s", bots.size(), qc.numSyntheticBots, SurveyResponse.newline)); for (SurveyResponse sr : bots){ bw.write(sr.srid + sep + sr.real + sep + sr.score); for (QuestionResponse qr : sr.responses) for (Tuple2<Component, Integer> tupe : qr.opts) bw.write(sep + tupe._1().getCid()); bw.write(SurveyResponse.newline); } bw.close(); } }
package cc.co.traviswatkins; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Event.Priority; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.nijiko.permissions.PermissionHandler; import java.util.List; import net.minecraft.server.EntityHuman; import net.minecraft.server.Packet20NamedEntitySpawn; import net.minecraft.server.Packet29DestroyEntity; import org.bukkit.craftbukkit.entity.CraftPlayer; public class ModMode extends JavaPlugin { public static PermissionHandler permissionHandler; private SerializedPersistance persistance; private Set<String> invisible = new HashSet<String>(); public Set<String> modmode = new HashSet<String>(); private final ModModeEntityListener entityListener = new ModModeEntityListener(this); private final ModModePlayerListener playerListener = new ModModePlayerListener(this); protected static final Logger log = Logger.getLogger("Minecraft"); public boolean isPlayerInvisible(String name) { return invisible.contains(name); } public boolean isPlayerModMode(String name) { return modmode.contains(name); } @Override public void onDisable() { // get everyone out of mod mode to avoid issues Player[] onlinePlayers = this.getServer().getOnlinePlayers(); for (Player p : onlinePlayers) if (isPlayerModMode(p.getDisplayName())) disableModMode(p); log.log(Level.INFO, "[" + getDescription().getName() + ")] " + getDescription().getVersion() + " disabled."); } @Override public void onEnable() { PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Normal, this); pm.registerEvent(Event.Type.ENTITY_TRACK, entityListener, Priority.Low, this); pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_RESPAWN, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, playerListener, Priority.Normal, this); log.log(Level.INFO, "[" + getDescription().getName() +"] " + getDescription().getVersion() + " enabled."); } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage("Sorry, this plugin cannot be used from console"); return true; } if (command.getName().equalsIgnoreCase("vanish")) { if ((args.length == 1) && (args[0].equalsIgnoreCase("list"))) { return vanishList((Player)sender); } return enableVanish((Player)sender); } if (command.getName().equalsIgnoreCase("unvanish")) { return disableVanish((Player)sender); } if (command.getName().equalsIgnoreCase("modmode")) { if (args.length == 1 && args[0].equalsIgnoreCase("on")) return enableModMode((Player)sender); if (args.length == 1 && args[0].equalsIgnoreCase("off")) return disableModMode((Player)sender); } return false; } public boolean disableModMode(Player player) { if (!Permissions.hasPermission(player, Permissions.MODMODE_TOGGLE)) return false; if (!modmode.contains(player.getDisplayName())) { player.sendMessage(ChatColor.RED + "You are not in mod mode!"); return false; } modmode.remove(player.getDisplayName()); if (isPlayerInvisible(player.getName())) invisible.remove(player.getName()); ((CraftPlayer)player).getHandle().name = player.getDisplayName(); player.kickPlayer("You are no longer in mod mode!"); return true; } public boolean enableModMode(Player player) { if (!Permissions.hasPermission(player, Permissions.MODMODE_TOGGLE)) return false; if (modmode.contains(player.getDisplayName())) { player.sendMessage(ChatColor.RED + "You are already in mod mode!"); return false; } modmode.add(player.getDisplayName()); String newname = player.getDisplayName().length() > 11 ? player.getDisplayName().substring(0, 11) : player.getDisplayName(); ((CraftPlayer)player).getHandle().name = ChatColor.GREEN + newname + ChatColor.WHITE; player.getInventory().clear(); player.sendMessage(ChatColor.RED + "You are now in mod mode."); boolean unlimited = Permissions.hasPermission(player, Permissions.UNVANISH_UNLIMITED); if (!unlimited) invisible.add(player.getName()); Player[] onlinePlayers = this.getServer().getOnlinePlayers(); for (Player p : onlinePlayers) { if (p.getEntityId() == player.getEntityId()) continue; if (unlimited || Permissions.hasPermission(p, Permissions.VANISH_SHOWHIDDEN)) { ((CraftPlayer)p).getHandle().netServerHandler.sendPacket(new Packet29DestroyEntity(player.getEntityId())); ((CraftPlayer)p).getHandle().netServerHandler.sendPacket(new Packet20NamedEntitySpawn((EntityHuman) ((CraftPlayer)player).getHandle())); } else { ((CraftPlayer)p).getHandle().netServerHandler.sendPacket(new Packet29DestroyEntity(player.getEntityId())); } } return true; } public boolean disableVanish(Player player) { if (!Permissions.hasPermission(player, Permissions.UNVANISH)) return false; if (!isPlayerInvisible(player.getName())) { player.sendMessage(ChatColor.RED + "You are not vanished!"); return true; } invisible.remove(player.getName()); Player[] onlinePlayers = this.getServer().getOnlinePlayers(); for (Player p : onlinePlayers) { if (p.getEntityId() == player.getEntityId()) continue; if (Permissions.hasPermission(p, Permissions.VANISH_SHOWHIDDEN)) continue; List<Player> trackers = p.getTrackers(); trackers.add(player); p.setTrackers(trackers); ((CraftPlayer)p).getHandle().netServerHandler.sendPacket(new Packet20NamedEntitySpawn((EntityHuman) ((CraftPlayer)player).getHandle())); } log.log(Level.INFO, player.getName() + " reappeared."); player.sendMessage(ChatColor.RED + "You have reappeared!"); return true; } public boolean enableVanish(Player player) { if (!Permissions.hasPermission(player, Permissions.VANISH)) return false; if (!isPlayerInvisible(player.getName())) invisible.add(player.getName()); Player[] onlinePlayers = this.getServer().getOnlinePlayers(); for (Player p : onlinePlayers) { if (p.getEntityId() == player.getEntityId()) continue; if (Permissions.hasPermission(p, Permissions.VANISH_SHOWHIDDEN)) continue; List<Player> trackers = p.getTrackers(); trackers.remove(player); p.setTrackers(trackers); ((CraftPlayer)p).getHandle().netServerHandler.sendPacket(new Packet29DestroyEntity(player.getEntityId())); } log.log(Level.INFO, player.getName() + " disappeared."); player.sendMessage(ChatColor.RED + "Poof!"); return true; } private boolean vanishList(Player player) { if (!Permissions.hasPermission(player, Permissions.VANISH_LIST)) return false; if (invisible.isEmpty()) { player.sendMessage(ChatColor.RED + "Everyone is visible"); return true; } String message = "Invisible Players: "; int i = 0; for (String name : invisible) { message += name; i++; if (i != invisible.size()) { message += " "; } } player.sendMessage(ChatColor.RED + message); return true; } }
package ch.ntb.inf.deep.ssa; import ch.ntb.inf.deep.cfg.CFGNode; import ch.ntb.inf.deep.classItems.ICdescAndTypeConsts; import ch.ntb.inf.deep.classItems.ICjvmInstructionOpcs; import ch.ntb.inf.deep.classItems.Class; import ch.ntb.inf.deep.classItems.StdConstant; import ch.ntb.inf.deep.classItems.DataItem; import ch.ntb.inf.deep.classItems.Item; import ch.ntb.inf.deep.classItems.Method; import ch.ntb.inf.deep.classItems.StringLiteral; import ch.ntb.inf.deep.classItems.Type; import ch.ntb.inf.deep.ssa.instruction.Call; import ch.ntb.inf.deep.ssa.instruction.Dyadic; import ch.ntb.inf.deep.ssa.instruction.DyadicRef; import ch.ntb.inf.deep.ssa.instruction.Monadic; import ch.ntb.inf.deep.ssa.instruction.MonadicRef; import ch.ntb.inf.deep.ssa.instruction.NoOpnd; import ch.ntb.inf.deep.ssa.instruction.NoOpndRef; import ch.ntb.inf.deep.ssa.instruction.PhiFunction; import ch.ntb.inf.deep.ssa.instruction.SSAInstruction; import ch.ntb.inf.deep.ssa.instruction.StoreToArray; import ch.ntb.inf.deep.ssa.instruction.Branch; import ch.ntb.inf.deep.strings.HString; /** * @author millischer */ public class SSANode extends CFGNode implements ICjvmInstructionOpcs, SSAInstructionOpcs, ICdescAndTypeConsts { boolean traversed; public int nofInstr; public int nofPhiFunc; public int nofDeletedPhiFunc; // its used for junit tests public int maxLocals; public int maxStack; private int stackpointer; public SSAValue exitSet[]; public SSAValue entrySet[]; public PhiFunction phiFunctions[]; public SSAInstruction instructions[]; public int codeStartAddr, codeEndAddr; public SSANode() { super(); instructions = new SSAInstruction[4]; phiFunctions = new PhiFunction[2]; traversed = false; nofInstr = 0; nofPhiFunc = 0; nofDeletedPhiFunc = 0; maxLocals = 0; maxStack = 0; } /** * The state arrays of the predecessors nodes of this node are merged into * the new entry set. phi-functions are created, if there is more then one * predecessor. iterates over all the bytecode instructions, emits SSA * instructions and modifies the state array */ public void mergeAndDetermineStateArray(SSA ssa) { maxLocals = ssa.cfg.method.getMaxLocals(); maxStack = ssa.cfg.method.getMaxStckSlots(); // check if all predecessors have their state array set if (!isLoopHeader()) { for (int i = 0; i < nofPredecessors && predecessors[i] != null; i++) { if (((SSANode) predecessors[i]).exitSet == null) { assert false : "exit set of predecessor is empty"; } } } if (nofPredecessors == 0) { // create new entry and exit sets, locals are uninitialized entrySet = new SSAValue[maxStack + maxLocals]; } else if (nofPredecessors == 1) { // only one predecessor --> no merge necessary if (this.equals(predecessors[0]) || ((SSANode) predecessors[0]).exitSet == null) {// equal by // "while(true){} entrySet = new SSAValue[maxStack + maxLocals]; } else { entrySet = ((SSANode) predecessors[0]).exitSet.clone(); } } else if (nofPredecessors >= 2) { // multiple predecessors --> merge necessary if (isLoopHeader()) { // if true --> generate phi functions for all locals // if we have redundant phi functions, we eliminate it later if (!traversed) { // first visit --> insert phi function with 1 parameter // swap on the index 0 a predecessor thats already processed for (int i = 0; i < nofPredecessors; i++) { if (((SSANode) predecessors[i]).exitSet != null) { SSANode temp = (SSANode) predecessors[i]; predecessors[i] = predecessors[0]; predecessors[0] = temp; } } if (((SSANode) predecessors[0]).exitSet == null) { // if this ist the root node and this is a loopheader // from case while(true){..} entrySet = new SSAValue[maxStack + maxLocals]; } else { entrySet = ((SSANode) predecessors[0]).exitSet.clone(); } for (int i = 0; i < maxStack + maxLocals; i++) { SSAValue result = new SSAValue(); result.index = i; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; if (entrySet[i] != null) { phi.result.type = entrySet[i].type; phi.addOperand(entrySet[i]); } addPhiFunction(phi); // Stack will be set when it is necessary; if (i >= maxStack || entrySet[i] != null) { entrySet[i] = result; } } } else { // skip the first already processed predecessor for (int i = 1; i < nofPredecessors; i++) { for (int j = 0; j < maxStack + maxLocals; j++) { SSAValue param = ((SSANode) predecessors[i]).exitSet[j]; SSAValue temp = param; // store // Check if it need a loadParam instruction if (ssa.isParam[j]&& (phiFunctions[j].nofOperands == 0 || param == null)) { param = generateLoadParameter((SSANode) idom, j, ssa); } if (temp != null && temp != param) { phiFunctions[j].addOperand(temp); phiFunctions[j].result.type = temp.type; } if (param != null) {// stack could be empty phiFunctions[j].addOperand(param); phiFunctions[j].result.type = param.type; } } } // second visit, merge is finished // eliminate redundant PhiFunctions eliminateRedundantPhiFunc(); } } else { // it isn't a loop header for (int i = 0; i < nofPredecessors; i++) { if (entrySet == null) { // first predecessor --> create locals entrySet = ((SSANode) predecessors[i]).exitSet.clone(); } else { // all other predecessors --> merge for (int j = 0; j < maxStack + maxLocals; j++) { // if both null, do nothing if (entrySet[j] != null || ((SSANode) predecessors[i]).exitSet[j] != null) { if (entrySet[j] == null) {// predecessor is set if (ssa.isParam[j]) { // create phi function SSAValue result = new SSAValue(); result.index = j; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; entrySet[j] = result; // generate for all already proceed // predecessors a loadParameter // and add their results to the phi // function for (int x = 0; x < i; x++) { phi.addOperand(generateLoadParameter((SSANode) predecessors[x],j, ssa)); } phi.addOperand(((SSANode) predecessors[i]).exitSet[j]); result.type = ((SSANode) predecessors[i]).exitSet[j].type; addPhiFunction(phi); } } else {// entrySet[j] != null // if both equals, do nothing if (!(entrySet[j].equals(((SSANode) predecessors[i]).exitSet[j]))) { if (((SSANode) predecessors[i]).exitSet[j] == null) { if (ssa.isParam[j]) { if (entrySet[j].owner.ssaOpcode == sCPhiFunc) { PhiFunction func = null; for (int y = 0; y < nofPhiFunc; y++) { if (entrySet[j].equals(phiFunctions[y].result)) { func = phiFunctions[y]; break; } } if (func == null) { SSAValue result = new SSAValue(); result.index = j; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; phi.addOperand(entrySet[j]); phi.result.type = entrySet[j].type; phi.addOperand(generateLoadParameter((SSANode) predecessors[i], j, ssa)); entrySet[j] = result; addPhiFunction(phi); } else { // phi functions are created in this node SSAValue temp = generateLoadParameter((SSANode) predecessors[i],j, ssa); func.result.type = temp.type; func.addOperand(temp); } } else { // entrySet[j] != SSAValue.tPhiFunc SSAValue result = new SSAValue(); result.index = j; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; phi.addOperand(entrySet[j]); phi.result.type = entrySet[j].type; phi.addOperand(generateLoadParameter((SSANode) predecessors[i], j, ssa)); entrySet[j] = result; addPhiFunction(phi); } } else { entrySet[j] = null; } } else { // entrySet[j] != null && ((SSANode) predecessors[i]).exitSet[j] != null if (entrySet[j].owner.ssaOpcode == sCPhiFunc) { PhiFunction func = null; for (int y = 0; y < nofPhiFunc; y++) { if (entrySet[j].equals(phiFunctions[y].result)) { func = phiFunctions[y]; break; } } if (func == null) { SSAValue result = new SSAValue(); result.index = j; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; phi.addOperand(entrySet[j]); phi.result.type = entrySet[j].type; phi.addOperand(((SSANode) predecessors[i]).exitSet[j]); entrySet[j] = result; addPhiFunction(phi); } else { // phi functions are created in this node //check if operands are from same type SSAValue[] opnd = func.getOperands(); // determine type // int type = opnd[0].type; // for (int y = 0; y < opnd.length - 1 && opnd[y].owner.ssaOpcode == sCPhiFunc; y++) { // type = opnd[y + 1].type; // if (type != SSAValue.tPhiFunc && ((SSANode) predecessors[i]).exitSet[j].type != SSAValue.tPhiFunc) { if (opnd[0].type == ((SSANode) predecessors[i]).exitSet[j].type) { func.addOperand(((SSANode) predecessors[i]).exitSet[j]); } else { // delete all Operands so the function will be deleted in the // method eleminateRedundantPhiFunc() func.setOperands(new SSAValue[0]); func.result.type = -1; entrySet[j] = null; } // } else { // func.addOperand(((SSANode) predecessors[i]).exitSet[j]); } } else { // entrySet[j].owner.ssaOpcode != sCPhiFunc if (entrySet[j].type == ((SSANode) predecessors[i]).exitSet[j].type) { SSAValue result = new SSAValue(); result.index = j; PhiFunction phi = new PhiFunction(sCPhiFunc); result.owner = phi; phi.result = result; phi.addOperand(entrySet[j]); phi.result.type = entrySet[j].type; phi.addOperand(((SSANode) predecessors[i]).exitSet[j]); addPhiFunction(phi); entrySet[j] = result; } else { entrySet[j] = null; } } } } } } } } } // isn't a loop header and merge is finished. // eliminate redundant phiFunctins eliminateRedundantPhiFunc(); } } // fill instruction array if (!traversed) { traversed = true; this.traversCode(ssa); } } public void traversCode(SSA ssa) { SSAValue value1, value2, value3, value4, result; SSAValue[] operands; int val, val1; DataItem field; SSAInstruction instr; boolean wide = false; exitSet = entrySet.clone();// Don't change the entry set // determine top of the stack for (stackpointer = maxStack - 1; stackpointer >= 0 && exitSet[stackpointer] == null; stackpointer ; for (int bca = this.firstBCA; bca <= this.lastBCA; bca++) { switch (ssa.cfg.code[bca] & 0xff) { case bCnop: break; case bCaconst_null: result = new SSAValue(); result.type = SSAValue.tRef; result.constant = null; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_m1: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(-1, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_0: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(0, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_1: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(1, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_2: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(2, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_3: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(3, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_4: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(4, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiconst_5: result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(5, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClconst_0: result = new SSAValue(); result.type = SSAValue.tLong; result.constant = new StdConstant(0, 0); result.constant.type = Type.wellKnownTypes[txLong]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClconst_1: result = new SSAValue(); result.type = SSAValue.tLong; result.constant = new StdConstant(0, 1); result.constant.type = Type.wellKnownTypes[txLong]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfconst_0: result = new SSAValue(); result.type = SSAValue.tFloat; result.constant = new StdConstant(Float.floatToIntBits(0.0f), 0); result.constant.type = Type.wellKnownTypes[txFloat]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfconst_1: result = new SSAValue(); result.type = SSAValue.tFloat; result.constant = new StdConstant(Float.floatToIntBits(1.0f), 0); result.constant.type = Type.wellKnownTypes[txFloat]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfconst_2: result = new SSAValue(); result.type = SSAValue.tFloat; result.constant = new StdConstant(Float.floatToIntBits(2.0f), 0); result.constant.type = Type.wellKnownTypes[txFloat]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdconst_0: result = new SSAValue(); result.type = SSAValue.tDouble; result.constant = new StdConstant((int) (Double .doubleToLongBits(0.0) >> 32), (int) (Double .doubleToLongBits(0.0))); result.constant.type = Type.wellKnownTypes[txDouble]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdconst_1: result = new SSAValue(); result.type = SSAValue.tDouble; result.constant = new StdConstant((int) (Double .doubleToLongBits(1.0) >> 32), (int) (Double .doubleToLongBits(1.0))); result.constant.type = Type.wellKnownTypes[txDouble]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCbipush: // get byte from Bytecode bca++; val = ssa.cfg.code[bca];// sign-extended result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(val, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCsipush: // get short from Bytecode bca++; short sval = (short) (((ssa.cfg.code[bca++] & 0xff) << 8) | (ssa.cfg.code[bca] & 0xff)); val = sval;// sign-extended to int result = new SSAValue(); result.type = SSAValue.tInteger; result.constant = new StdConstant(val, 0); result.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCldc: bca++; val = ssa.cfg.code[bca]; result = new SSAValue(); if (ssa.cfg.method.owner.constPool[val] instanceof StdConstant) { StdConstant constant = (StdConstant) ssa.cfg.method.owner.constPool[val]; if (constant.type.name.charAt(0) == 'I') {// is a int result.type = SSAValue.tInteger; result.constant = constant; } else { if (constant.type.name.charAt(0) == 'F') { // is a float result.type = SSAValue.tFloat; result.constant = constant; // result.constant = // Float.intBitsToFloat(constant.valueH); } else { assert false : "Wrong Constant type"; } } } else { if (ssa.cfg.method.owner.constPool[val] instanceof StringLiteral) { // String StringLiteral literal = (StringLiteral) ssa.cfg.method.owner.constPool[val]; result.type = SSAValue.tRef; result.constant = literal; // result.constant = literal.string; } else { assert false : "Wrong DataItem type"; break; } } instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCldc_w: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); if (ssa.cfg.method.owner.constPool[val] instanceof StdConstant) { StdConstant constant = (StdConstant) ssa.cfg.method.owner.constPool[val]; if (constant.type.name.charAt(0) == 'I') {// is a int result.type = SSAValue.tInteger; result.constant = constant; } else { if (constant.type.name.charAt(0) == 'F') { // is a float result.type = SSAValue.tFloat; result.constant = constant; // result.constant = // Float.intBitsToFloat(constant.valueH); } else { assert false : "Wrong Constant type"; } } } else { if (ssa.cfg.method.owner.constPool[val] instanceof StringLiteral) { // String StringLiteral literal = (StringLiteral) ssa.cfg.method.owner.constPool[val]; result.type = SSAValue.tRef; result.constant = literal; // result.constant = literal.string; } else { assert false : "Wrong DataItem type"; break; } } instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCldc2_w: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); if (ssa.cfg.method.owner.constPool[val] instanceof StdConstant) { StdConstant constant = (StdConstant) ssa.cfg.method.owner.constPool[val]; if (constant.type.name.charAt(0) == 'D') {// is a Double result.type = SSAValue.tDouble; result.constant = constant; } else { if (constant.type.name.charAt(0) == 'J') { // is a Long result.type = SSAValue.tLong; result.constant = constant; } else { assert false : "Wrong Constant type"; } } } else { assert false : "Wrong DataItem type"; break; } instr = new NoOpnd(sCloadConst); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiload: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } load(val, SSAValue.tInteger); break; case bClload: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } load(val, SSAValue.tLong); break; case bCfload: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } load(val, SSAValue.tFloat); break; case bCdload: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } load(val, SSAValue.tDouble); break; case bCaload: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } load(val, SSAValue.tRef); break; case bCiload_0: load(0, SSAValue.tInteger); break; case bCiload_1: load(1, SSAValue.tInteger); break; case bCiload_2: load(2, SSAValue.tInteger); break; case bCiload_3: load(3, SSAValue.tInteger); break; case bClload_0: load(0, SSAValue.tLong); break; case bClload_1: load(1, SSAValue.tLong); break; case bClload_2: load(2, SSAValue.tLong); break; case bClload_3: load(3, SSAValue.tLong); break; case bCfload_0: load(0, SSAValue.tFloat); break; case bCfload_1: load(1, SSAValue.tFloat); break; case bCfload_2: load(2, SSAValue.tFloat); break; case bCfload_3: load(3, SSAValue.tFloat); break; case bCdload_0: load(0, SSAValue.tDouble); break; case bCdload_1: load(1, SSAValue.tDouble); break; case bCdload_2: load(2, SSAValue.tDouble); break; case bCdload_3: load(3, SSAValue.tDouble); break; case bCaload_0: load(0, SSAValue.tRef); break; case bCaload_1: load(1, SSAValue.tRef); break; case bCaload_2: load(2, SSAValue.tRef); break; case bCaload_3: load(3, SSAValue.tRef); break; case bCiaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCaaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tRef; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCbaload: // Remember the result type isn't set here (it could be boolean // or byte) value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tByte; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCcaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tChar; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCsaload: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tShort; instr = new Dyadic(sCloadFromArray, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCistore: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + val); exitSet[maxStack + val].index = maxStack + val; break; case bClstore: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + val); exitSet[maxStack + val].index = maxStack + val; break; case bCfstore: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + val); exitSet[maxStack + val].index = maxStack + val; break; case bCdstore: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + val); exitSet[maxStack + val].index = maxStack + val; break; case bCastore: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // index wide = false; } else { val = (ssa.cfg.code[bca] & 0xff);// get index } // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + val); exitSet[maxStack + val].index = maxStack + val; break; case bCistore_0: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack); exitSet[maxStack].index = maxStack; break; case bCistore_1: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 1); exitSet[maxStack + 1].index = maxStack + 1; break; case bCistore_2: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 2); exitSet[maxStack + 2].index = maxStack + 2; break; case bCistore_3: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 3); exitSet[maxStack + 3].index = maxStack + 3; break; case bClstore_0: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack); exitSet[maxStack].index = maxStack; break; case bClstore_1: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 1); exitSet[maxStack + 1].index = maxStack + 1; break; case bClstore_2: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 2); exitSet[maxStack + 2].index = maxStack + 2; break; case bClstore_3: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 3); exitSet[maxStack + 3].index = maxStack + 3; break; case bCfstore_0: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack); exitSet[maxStack].index = maxStack; break; case bCfstore_1: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 1); exitSet[maxStack + 1].index = maxStack + 1; break; case bCfstore_2: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 2); exitSet[maxStack + 2].index = maxStack + 2; break; case bCfstore_3: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 3); exitSet[maxStack + 3].index = maxStack + 3; break; case bCdstore_0: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack); exitSet[maxStack].index = maxStack; break; case bCdstore_1: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 1); exitSet[maxStack + 1].index = maxStack + 1; break; case bCdstore_2: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 2); exitSet[maxStack + 2].index = maxStack + 2; break; case bCdstore_3: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 3); exitSet[maxStack + 3].index = maxStack + 3; break; case bCastore_0: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack); exitSet[maxStack].index = maxStack; break; case bCastore_1: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 1); exitSet[maxStack + 1].index = maxStack + 1; break; case bCastore_2: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 2); exitSet[maxStack + 2].index = maxStack + 2; break; case bCastore_3: // create register moves in creating of SSA was wished by U.Graf insertRegMoves(maxStack + 3); exitSet[maxStack + 3].index = maxStack + 3; break; case bCiastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bClastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCfastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCdastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCaastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCbastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCcastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCsastore: value3 = popFromStack(); value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tVoid; instr = new StoreToArray(sCstoreToArray, value1, value2, value3); instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCpop: popFromStack(); break; case bCpop2: value1 = popFromStack(); // false if value1 is a value of a category 2 computational type if (!((value1.type == SSAValue.tLong) || (value1.type == SSAValue.tDouble))) { popFromStack(); } break; case bCdup: value1 = popFromStack(); pushToStack(value1); pushToStack(value1); break; case bCdup_x1: value1 = popFromStack(); value2 = popFromStack(); pushToStack(value1); pushToStack(value2); pushToStack(value1); break; case bCdup_x2: value1 = popFromStack(); value2 = popFromStack(); // true if value2 is a value of a category 2 computational type if ((value2.type == SSAValue.tLong) || (value2.type == SSAValue.tDouble)) { pushToStack(value1); pushToStack(value2); pushToStack(value1); } else { value3 = popFromStack(); pushToStack(value1); pushToStack(value3); pushToStack(value2); pushToStack(value1); } break; case bCdup2: value1 = popFromStack(); // true if value1 is a value of a category 2 computational type if ((value1.type == SSAValue.tLong) || (value1.type == SSAValue.tDouble)) { pushToStack(value1); pushToStack(value1); } else { value2 = popFromStack(); pushToStack(value2); pushToStack(value1); pushToStack(value2); pushToStack(value1); } break; case bCdup2_x1: value1 = popFromStack(); value2 = popFromStack(); // true if value1 is a value of a category 2 computational type if ((value1.type == SSAValue.tLong) || (value1.type == SSAValue.tDouble)) { pushToStack(value1); pushToStack(value2); pushToStack(value1); } else { value3 = popFromStack(); pushToStack(value2); pushToStack(value1); pushToStack(value3); pushToStack(value2); pushToStack(value1); } break; case bCdup2_x2: value1 = popFromStack(); value2 = popFromStack(); // true if value1 is a value of a category 2 computational type if ((value1.type == SSAValue.tLong) || (value1.type == SSAValue.tDouble)) { // true if value2 is a value of a category 2 computational type //Form4 (the java virtual Machine Specification secondedition, Tim Lindholm, Frank Yellin, page 223) if ((value2.type == SSAValue.tLong) || (value2.type == SSAValue.tDouble)) { pushToStack(value1); pushToStack(value2); pushToStack(value1); } else { // Form 2 (the java virtual Machine Specification second // edition, Tim Lindholm, Frank Yellin, page 223) value3 = popFromStack(); pushToStack(value1); pushToStack(value3); pushToStack(value2); pushToStack(value1); } } else { value3 = popFromStack(); // true if value3 is a value of a category 2 computational type // Form 3 (the java virtual Machine Specification second // edition, Tim Lindholm, Frank Yellin, page 223) if ((value3.type == SSAValue.tLong) || (value3.type == SSAValue.tDouble)) { pushToStack(value2); pushToStack(value1); pushToStack(value3); pushToStack(value2); pushToStack(value1); } else { // Form 1 (the java virtual Machine Specification second // edition, Tim Lindholm, Frank Yellin, page 223) value4 = popFromStack(); pushToStack(value2); pushToStack(value1); pushToStack(value4); pushToStack(value3); pushToStack(value2); pushToStack(value1); } } break; case bCswap: value1 = popFromStack(); value2 = popFromStack(); pushToStack(value1); pushToStack(value2); break; case bCiadd: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCadd, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCladd: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCadd, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfadd: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCadd, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdadd: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCadd, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCisub: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCsub, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClsub: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCsub, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfsub: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCsub, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdsub: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCsub, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCimul: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCmul, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClmul: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCmul, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfmul: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCmul, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdmul: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCmul, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCidiv: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCdiv, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCldiv: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCdiv, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfdiv: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCdiv, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCddiv: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCdiv, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCirem: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCrem, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClrem: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCrem, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfrem: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Dyadic(sCrem, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdrem: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Dyadic(sCrem, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCineg: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Monadic(sCneg, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClneg: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Monadic(sCneg, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfneg: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Monadic(sCneg, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdneg: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Monadic(sCneg, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCishl: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCshl, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClshl: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCshl, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCishr: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCshr, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClshr: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCshr, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiushr: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCushr, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClushr: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCushr, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiand: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCand, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCland: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCand, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCior: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCor, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClor: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCor, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCixor: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCxor, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClxor: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Dyadic(sCxor, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCiinc: bca++; if (wide) { val = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca++]) & 0xffff;// get // index val1 = ((ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]) & 0xffff;// get // const wide = false; } else { val = ssa.cfg.code[bca++];// get index val1 = ssa.cfg.code[bca];// get const } load(val, SSAValue.tInteger); value1 = popFromStack(); value2 = new SSAValue(); value2.type = SSAValue.tInteger; value2.constant = new StdConstant(val1, 0); value2.constant.type = Type.wellKnownTypes[txInt]; instr = new NoOpnd(sCloadConst); instr.result = value2; instr.result.owner = instr; addInstruction(instr); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCadd, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); exitSet[maxStack + val] = result; exitSet[maxStack + val].index = maxStack + val; break; case bCi2l: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCi2f: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCi2d: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCl2i: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Monadic(sCconvLong, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCl2f: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Monadic(sCconvLong, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCl2d: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Monadic(sCconvLong, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCf2i: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Monadic(sCconvFloat, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCf2l: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Monadic(sCconvFloat, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCf2d: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tDouble; instr = new Monadic(sCconvFloat, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCd2i: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Monadic(sCconvDouble, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCd2l: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tLong; instr = new Monadic(sCconvDouble, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCd2f: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tFloat; instr = new Monadic(sCconvDouble, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCi2b: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tByte; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCi2c: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tChar; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCi2s: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tShort; instr = new Monadic(sCconvInt, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bClcmp: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCcmpl, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfcmpl: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCcmpl, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCfcmpg: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCcmpg, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdcmpl: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCcmpl, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCdcmpg: value2 = popFromStack(); value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new Dyadic(sCcmpg, value1, value2); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCifeq: case bCifne: case bCiflt: case bCifge: case bCifgt: case bCifle: value1 = popFromStack(); instr = new Branch(sCbranch, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); bca = bca + 2; // step over branchbyte1 and branchbyte2 break; case bCif_icmpeq: case bCif_icmpne: case bCif_icmplt: case bCif_icmpge: case bCif_icmpgt: case bCif_icmple: case bCif_acmpeq: case bCif_acmpne: value1 = popFromStack(); value2 = popFromStack(); instr = new Branch(sCbranch, value1, value2); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); bca = bca + 2; // step over branchbyte1 and branchbyte2 break; case bCgoto: // val = (short) (ssa.cfg.code[bca + 1] & 0xff << 8 | // ssa.cfg.code[bca + 2]); instr = new Branch(sCbranch); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); bca = bca + 2; // step over branchbyte1 and branchbyte2 break; case bCjsr: // I think it isn't necessary to push the address onto the stack bca = bca + 2; // step over branchbyte1 and branchbyte2 break; case bCret: if (wide) { bca = bca + 2; // step over indexbyte1 and indexbyte2 wide = false; } else { bca++;// step over index } break; case bCtableswitch: value1 = popFromStack(); instr = new Branch(sCbranch, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // Step over whole bytecode instruction bca++; // pad bytes while ((bca & 0x03) != 0) { bca++; } // default jump address bca = bca + 4; // we need the low and high int low1 = (ssa.cfg.code[bca++] << 24) | (ssa.cfg.code[bca++] << 16) | (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca++]; int high1 = (ssa.cfg.code[bca++] << 24) | (ssa.cfg.code[bca++] << 16) | (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca++]; int nofPair1 = high1 - low1 + 1; // jump offsets bca = bca + 4 * nofPair1 - 1; break; case bClookupswitch: value1 = popFromStack(); instr = new Branch(sCbranch, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // Step over whole bytecode instruction bca++; // pad bytes while ((bca & 0x03) != 0) { bca++; } // default jump adress bca = bca + 4; // npairs int nofPair2 = (ssa.cfg.code[bca++] << 24) | (ssa.cfg.code[bca++] << 16) | (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca++]; // jump offsets bca = bca + 8 * nofPair2 - 1; break; case bCireturn: value1 = popFromStack(); instr = new Branch(sCreturn, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bClreturn: value1 = popFromStack(); instr = new Branch(sCreturn, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bCfreturn: value1 = popFromStack(); instr = new Branch(sCreturn, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bCdreturn: value1 = popFromStack(); instr = new Branch(sCreturn, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bCareturn: value1 = popFromStack(); instr = new Branch(sCreturn, value1); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bCreturn: instr = new Branch(sCreturn); instr.result = new SSAValue(); instr.result.owner = instr; addInstruction(instr); // discard Stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } break; case bCgetstatic: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); // determine the type of the field if (!(ssa.cfg.method.owner.constPool[val] instanceof DataItem)) { assert false : "Constantpool entry isn't a DataItem. Used in getstatic"; } field = (DataItem) ssa.cfg.method.owner.constPool[val]; if (field.type.name.charAt(0) == '[') { switch (field.type.name.charAt(1)) { case 'B': result.type = SSAValue.tAbyte; break; case 'C': result.type = SSAValue.tAchar; break; case 'D': result.type = SSAValue.tAdouble; break; case 'F': result.type = SSAValue.tAfloat; break; case 'I': result.type = SSAValue.tAinteger; break; case 'J': result.type = SSAValue.tAlong; break; case 'S': result.type = SSAValue.tAshort; break; case 'Z': result.type = SSAValue.tAboolean; break; case 'L': result.type = SSAValue.tAref; break; default: result.type = SSAValue.tVoid; } } else { switch (field.type.name.charAt(0)) { case 'B': result.type = SSAValue.tByte; break; case 'C': result.type = SSAValue.tChar; break; case 'D': result.type = SSAValue.tDouble; break; case 'F': result.type = SSAValue.tFloat; break; case 'I': result.type = SSAValue.tInteger; break; case 'J': result.type = SSAValue.tLong; break; case 'S': result.type = SSAValue.tShort; break; case 'Z': result.type = SSAValue.tBoolean; break; case 'L': result.type = SSAValue.tRef; // TODO mit Ernst besprechen, wiso field.type.name nie // mit einem L beginnt? break; default: result.type = SSAValue.tRef; } } instr = new NoOpndRef(sCloadFromField, field); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCputstatic: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); result.type = SSAValue.tVoid; value1 = popFromStack(); if (ssa.cfg.method.owner.constPool[val] instanceof DataItem) { instr = new MonadicRef(sCstoreToField, (DataItem) ssa.cfg.method.owner.constPool[val], value1); } else { instr = null; assert false : "Constantpool entry isn't a DataItem. Used in putstatic"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCgetfield: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); // determine the type of the field field = (DataItem) ssa.cfg.method.owner.constPool[val]; if (field.type.name.charAt(0) == '[') { switch (field.type.name.charAt(1)) { case 'B': result.type = SSAValue.tAbyte; break; case 'C': result.type = SSAValue.tAchar; break; case 'D': result.type = SSAValue.tAdouble; break; case 'F': result.type = SSAValue.tAfloat; break; case 'I': result.type = SSAValue.tAinteger; break; case 'J': result.type = SSAValue.tAlong; break; case 'S': result.type = SSAValue.tAshort; break; case 'Z': result.type = SSAValue.tAboolean; break; case 'L': result.type = SSAValue.tAref; break; default: result.type = SSAValue.tVoid; } } else { switch (field.type.name.charAt(0)) { case 'B': result.type = SSAValue.tByte; break; case 'C': result.type = SSAValue.tChar; break; case 'D': result.type = SSAValue.tDouble; break; case 'F': result.type = SSAValue.tFloat; break; case 'I': result.type = SSAValue.tInteger; break; case 'J': result.type = SSAValue.tLong; break; case 'S': result.type = SSAValue.tShort; break; case 'Z': result.type = SSAValue.tBoolean; break; case 'L': result.type = SSAValue.tRef; // TODO mit Ernst besprechen, wiso field.type.name nie // mit einem L beginnt? break; default: result.type = SSAValue.tVoid; } } value1 = popFromStack(); if (ssa.cfg.method.owner.constPool[val] instanceof DataItem) { instr = new MonadicRef(sCloadFromField, (DataItem) ssa.cfg.method.owner.constPool[val], value1); } else { instr = null; assert false : "Constantpool entry isn't a DataItem. Used in getfield"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCputfield: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); result.type = SSAValue.tVoid; value2 = popFromStack(); value1 = popFromStack(); if (ssa.cfg.method.owner.constPool[val] instanceof DataItem) { instr = new DyadicRef(sCstoreToField, (DataItem) ssa.cfg.method.owner.constPool[val], value1, value2); } else { instr = null; assert false : "Constantpool entry isn't a DataItem. Used in putfield"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); break; case bCinvokevirtual: bca++; // index into cp val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; // cp entry must be a MethodItem val1 = ((Method) ssa.cfg.method.owner.constPool[val]).nofParams; operands = new SSAValue[val1 + 1];// objectref + nargs for (int i = operands.length - 1; i > -1; i operands[i] = popFromStack(); } result = new SSAValue(); result.type = decodeReturnDesc( ((Method) ssa.cfg.method.owner.constPool[val]).methDescriptor, ssa); instr = new Call(sCcall, ((Method) ssa.cfg.method.owner.constPool[val]), operands); instr.result = result; instr.result.owner = instr; addInstruction(instr); if (result.type != SSAValue.tVoid) { pushToStack(result); } break; case bCinvokespecial: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; // cp entry must be a MethodItem val1 = ((Method) ssa.cfg.method.owner.constPool[val]).nofParams; operands = new SSAValue[val1 + 1];// objectref + nargs for (int i = operands.length - 1; i > -1; i operands[i] = popFromStack(); } result = new SSAValue(); result.type = decodeReturnDesc( ((Method) ssa.cfg.method.owner.constPool[val]).methDescriptor, ssa); instr = new Call(sCcall, ((Method) ssa.cfg.method.owner.constPool[val]), operands); instr.result = result; instr.result.owner = instr; ((Call) instr).invokespecial = true; addInstruction(instr); if (result.type != SSAValue.tVoid) { pushToStack(result); } break; case bCinvokestatic: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; // cp entry must be a MethodItem val1 = ((Method) ssa.cfg.method.owner.constPool[val]).nofParams; operands = new SSAValue[val1];// nargs for (int i = operands.length - 1; i > -1; i operands[i] = popFromStack(); } result = new SSAValue(); result.type = decodeReturnDesc( ((Method) ssa.cfg.method.owner.constPool[val]).methDescriptor, ssa); instr = new Call(sCcall, ((Method) ssa.cfg.method.owner.constPool[val]), operands); instr.result = result; instr.result.owner = instr; addInstruction(instr); if (result.type != SSAValue.tVoid) { pushToStack(result); } break; case bCinvokeinterface: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; bca = bca + 2;// step over count and zero byte // cp entry must be a MethodItem val1 = ((Method) ssa.cfg.method.owner.constPool[val]).nofParams; operands = new SSAValue[val1 + 1];// objectref + nargs for (int i = operands.length - 1; i > -1; i operands[i] = popFromStack(); } result = new SSAValue(); result.type = decodeReturnDesc( ((Method) ssa.cfg.method.owner.constPool[val]).methDescriptor, ssa); instr = new Call(sCcall, ((Method) ssa.cfg.method.owner.constPool[val]), operands); instr.result = result; instr.result.owner = instr; addInstruction(instr); if (result.type != SSAValue.tVoid) { pushToStack(result); } break; case bCnew: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; // value1 = new SSAValue(); result = new SSAValue(); Item type = null; if (ssa.cfg.method.owner.constPool[val] instanceof Class) { type = ssa.cfg.method.owner.constPool[val]; // value1.type = SSAValue.tRef; // value1.constant = clazz; } else { // it is a Array of objects if (ssa.cfg.method.owner.constPool[val] instanceof Type) { assert false : "why a type?"; // Item type = ssa.cfg.method.owner.constPool[val]; // result.type = SSAValue.tAref; // result.constant = type.type; } else { assert false : "Unknown Parametertype for new"; break; } } result.type = SSAValue.tRef; // instr = new Call(sCnew, new SSAValue[] { value1 }); instr = new Call(sCnew, type); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCnewarray: bca++; val = ssa.cfg.code[bca] & 0xff;// atype value1 = popFromStack(); result = new SSAValue(); result.type = val + 10; SSAValue[] operand = { value1 }; instr = new Call(sCnew, operand); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCanewarray: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; result = new SSAValue(); result.type = SSAValue.tAref; value1 = popFromStack(); SSAValue[] opnd = { value1 }; if (ssa.cfg.method.owner.constPool[val] instanceof Type) { instr = new Call(sCnew, ((Type) ssa.cfg.method.owner.constPool[val]), opnd); } else { instr = null; assert false : "Constantpool entry isn't a class, array or interface type. Used in anewarray"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCarraylength: value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; instr = new MonadicRef(sCalength, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCathrow: value1 = popFromStack(); result = value1; instr = new Monadic(sCthrow, value1); instr.result = result; instr.result.owner = instr; addInstruction(instr); // clear stack while (stackpointer >= 0) { exitSet[stackpointer] = null; stackpointer } pushToStack(result); break; case bCcheckcast: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; value1 = popFromStack(); result = value1; if (ssa.cfg.method.owner.constPool[val] instanceof Type) { instr = new MonadicRef(sCthrow, (Type) ssa.cfg.method.owner.constPool[val], value1); } else { instr = null; assert false : "Constantpool entry isn't a class, array or interface type. Used in checkcast"; } instr.result = result; instr.result.owner = instr; pushToStack(value1); addInstruction(instr); break; case bCinstanceof: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca]; value1 = popFromStack(); result = new SSAValue(); result.type = SSAValue.tInteger; if (ssa.cfg.method.owner.constPool[val] instanceof Type) { instr = new MonadicRef(sCinstanceof, ((Type) ssa.cfg.method.owner.constPool[val]), value1); } else { instr = null; assert false : "Constantpool entry isn't a class, array or interface type. Used in instanceof"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCmonitorenter: popFromStack(); break; case bCmonitorexit: popFromStack(); break; case bCwide: wide = true; break; case bCmultianewarray: bca++; val = (ssa.cfg.code[bca++] << 8) | ssa.cfg.code[bca++]; val1 = ssa.cfg.code[bca]; result = new SSAValue(); result.type = SSAValue.tAref; operands = new SSAValue[val1]; for (int i = 0; i < operands.length; i++) { operands[i] = popFromStack(); } if (ssa.cfg.method.owner.constPool[val] instanceof Type) { instr = new Call(sCnew, ((Type) ssa.cfg.method.owner.constPool[val]), operands); } else { instr = null; assert false : "Constantpool entry isn't a class, array or interface type. Used in multianewarray"; } instr.result = result; instr.result.owner = instr; addInstruction(instr); pushToStack(result); break; case bCifnull: case bCifnonnull: value1 = popFromStack(); instr = new Branch(sCbranch, value1); instr.result = new SSAValue(); instr.result.owner = instr; bca = bca + 2; // step over branchbyte1 and branchbyte2 break; case bCgoto_w: bca = bca + 4; // step over branchbyte1 and branchbyte2... break; case bCjsr_w: // I think it isn't necessary to push the adress onto the stack bca = bca + 4; // step over branchbyte1 and branchbyte2... break; case bCbreakpoint: // do nothing break; default: // do nothing } } } private void pushToStack(SSAValue value) { if (stackpointer + 1 >= maxStack) { throw new IndexOutOfBoundsException("Stack overflow"); } exitSet[stackpointer + 1] = value; stackpointer++; } private SSAValue popFromStack() { SSAValue val; if (stackpointer < 0) { throw new IndexOutOfBoundsException("Empty Stack"); } val = exitSet[stackpointer]; exitSet[stackpointer] = null; stackpointer return val; } public void addInstruction(SSAInstruction instr) { int len = instructions.length; if (nofInstr == len) { SSAInstruction[] newArray = new SSAInstruction[2 * len]; for (int k = 0; k < len; k++) newArray[k] = instructions[k]; instructions = newArray; } if ((nofInstr > 0) && (instructions[nofInstr - 1].ssaOpcode == sCbranch)) { // insert // before // branch // instruction instructions[nofInstr] = instructions[nofInstr - 1]; instructions[nofInstr - 1] = instr; } else instructions[nofInstr] = instr; nofInstr++; } private void addPhiFunction(PhiFunction func) { int len = phiFunctions.length; if (nofPhiFunc == len) { PhiFunction[] newArray = new PhiFunction[2 * len]; for (int k = 0; k < len; k++) newArray[k] = phiFunctions[k]; phiFunctions = newArray; } phiFunctions[nofPhiFunc] = func; nofPhiFunc++; } private void load(int index, int type) { SSAValue result = exitSet[maxStack + index]; if (result == null) {// local isn't initialized result = new SSAValue(); result.type = type; result.index = index + maxStack; SSAInstruction instr = new NoOpnd(sCloadLocal); instr.result = result; instr.result.owner = instr; addInstruction(instr); exitSet[maxStack + index] = result; } pushToStack(result); } private SSAValue generateLoadParameter(SSANode predecessor, int index, SSA ssa) { boolean needsNewNode = false; SSANode node = predecessor; for (int i = 0; i < this.nofPredecessors; i++) { if (!this.predecessors[i].equals(predecessor) && !needsNewNode) { needsNewNode = this.idom.equals(predecessor) && !(this.equals(this.predecessors[i].idom)) && !isLoopHeader(); } } if (needsNewNode) { node = this.insertNode(predecessor, ssa); } SSAValue result = new SSAValue(); result.index = index; result.type = ssa.paramType[index]; SSAInstruction instr = new NoOpnd(sCloadLocal); instr.result = result; instr.result.owner = instr; node.addInstruction(instr); node.exitSet[index] = result; return result; } /** * * @param base * SSANode that immediate follow of predecessor * @param predecessor * SSANode that is immediate for the base node * @return on success the inserted SSANode, otherwise null */ public SSANode insertNode(SSANode predecessor, SSA ssa) { int index = -1; SSANode node = null; // check if base follows predecessor immediately a save index for (int i = 0; i < nofPredecessors; i++) { if (predecessors[i].equals(predecessor)) { index = i; break; } } if (index >= 0) { node = new SSANode(); node.firstBCA = -1; node.lastBCA = -1; node.maxLocals = this.maxLocals; node.maxStack = this.maxStack; node.idom = idom; node.entrySet = predecessor.exitSet.clone(); node.exitSet = node.entrySet.clone(); node.addSuccessor(this); predecessors[index] = node; node.addPredecessor(predecessor); for (int i = 0; i < predecessor.successors.length; i++) { if (predecessor.successors[i].equals(this)) { predecessor.successors[i] = node; break; } } } // insert node SSANode lastNode = (SSANode) ssa.cfg.rootNode; while ((lastNode.next != null) && (lastNode.next != this)) { lastNode = (SSANode) lastNode.next; } lastNode.next = node; node.next = this; return node; } /** * Eliminate phi functions that was unnecessarily generated. There are tow * Cases in which a phi function becomes redundant. * <p> * <b>Case 1:</b><br> * Phi functions of the form * * <pre> * x = [y,x,x,...,x] * </pre> * * can be replaced by y. * <p> * <b>Case 2:</b><br> * Phi functions of the form * * <pre> * x = [x,x,...,x] * </pre> * * can be replaced by x. * <p> */ public void eliminateRedundantPhiFunc() { SSAValue tempRes; SSAValue[] tempOperands; int indexOfDiff; boolean redundant, diffAlreadyOccured; int count = 0; PhiFunction[] temp = new PhiFunction[nofPhiFunc]; // Traverse phiFunctions for (int i = 0; i < nofPhiFunc; i++) { indexOfDiff = 0; redundant = true; diffAlreadyOccured = false; tempRes = phiFunctions[i].result; tempOperands = phiFunctions[i].getOperands(); // Compare result with operands. // determine if the function is redundant for (int j = 0; j < tempOperands.length; j++) { if (tempOperands[j].owner.ssaOpcode == sCPhiFunc) { // handle virtual deleted PhiFunctions special if (((PhiFunction) tempOperands[j].owner).deleted) { SSAValue res = tempOperands[j].owner.getOperands()[0]; while(res.owner.ssaOpcode == sCPhiFunc){//if is a phiFunction too if(((PhiFunction)res.owner).deleted){ if(res == res.owner.getOperands()[0]){//it is the same phiFunction break; } res = res.owner.getOperands()[0]; } else { break; } } if (res == tempOperands[j] || res.owner.ssaOpcode != sCPhiFunc) { // ignore operand he have no parent PhiFunctions // that lives continue; } else { tempOperands[j] = res;// protect for cycles } } } if (tempRes != (tempOperands[j])) { if (diffAlreadyOccured) { redundant = false; break; } diffAlreadyOccured = true; indexOfDiff = j; } } if (redundant) { // if the Phifunc has no parameter so delete it real if (phiFunctions[i].nofOperands > 0) { if (!phiFunctions[i].deleted) { // delete it virtually an set the operand for // replacement phiFunctions[i].deleted = true; phiFunctions[i] .setOperands(new SSAValue[] { tempOperands[indexOfDiff] }); nofDeletedPhiFunc++; } temp[count++] = phiFunctions[i]; } } else { temp[count++] = phiFunctions[i]; } } phiFunctions = temp; nofPhiFunc = count; } private int decodeReturnDesc(HString methodDescriptor, SSA ssa) { int type, i; char ch = methodDescriptor.charAt(0); for (i = 0; ch != ')'; i++) {// travers (....) we need only the // Returnvalue; ch = methodDescriptor.charAt(i); } ch = methodDescriptor.charAt(i++); if (ch == '[') { while (ch == '[') { i++; ch = methodDescriptor.charAt(i); } type = ssa.decodeFieldType(ch) + 10;// +10 is for Arrays } else { type = ssa.decodeFieldType(ch); } return type; } /** * Prints out the SSANode readable. * <p> * <b>Example:</b> * <p> * * <pre> * SSANode 0: * EntrySet {[ , ], [ , ]} * NoOpnd[sCloadConst] * Dyadic[sCadd] ( Integer, Integer ) * Dyadic[sCadd] ( Integer, Integer ) * Dyadic[sCadd] ( Integer, Integer ) * Monadic[sCloadVar] ( Void ) * NoOpnd[sCloadConst] * Dyadic[sCadd] ( Integer, Integer ) * ExitSet {[ , ], [ Integer (null), Integer (null) ]} * </pre> * * @param level * defines how much to indent * @param nodeNr * the Number of the node in this SSA */ public void print(int level, int nodeNr) { for (int i = 0; i < level * 3; i++) System.out.print(" "); System.out.println("SSANode " + nodeNr + ":"); // Print EntrySet with Stack and Locals for (int i = 0; i < (level + 1) * 3; i++) System.out.print(" "); System.out.print("EntrySet {"); if (entrySet.length > 0) System.out.print("[ "); for (int i = 0; i < entrySet.length - 1; i++) { if (entrySet[i] != null) System.out.print(entrySet[i].toString()); if (i == maxStack - 1) { System.out.print("], [ "); } else { System.out.print(", "); } } if (entrySet.length > 0) { if (entrySet[entrySet.length - 1] != null) { System.out.println(entrySet[entrySet.length - 1].toString() + " ]}"); } else { System.out.println("]}"); } } else { System.out.println("}"); } // Print Phifunctions for (int i = 0; i < nofPhiFunc; i++) { phiFunctions[i].print(level + 2); } // Print Instructions for (int i = 0; i < nofInstr; i++) { instructions[i].print(level + 2); } // Print ExitSet with Stack and Locals for (int i = 0; i < (level + 1) * 3; i++) System.out.print(" "); System.out.print("ExitSet {"); if (exitSet.length > 0) System.out.print("[ "); for (int i = 0; i < exitSet.length - 1; i++) { if (exitSet[i] != null) System.out.print(exitSet[i].toString()); if (i == maxStack - 1) { System.out.print("], [ "); } else { System.out.print(", "); } } if (exitSet.length > 0) { if (exitSet[exitSet.length - 1] != null) { System.out.println(exitSet[exitSet.length - 1].toString() + " ]}"); } else { System.out.println("]}"); } } else { System.out.println("}"); } } private void insertRegMoves(int index) { // create register moves in creating of SSA was wished by U.Graf SSAValue value1 = popFromStack(); // if(value1.type == SSAValue.tPhiFunc && value1.index > -1 && // value1.index != index){ if (value1.index > -1 && value1.index != index) { SSAValue r = new SSAValue(); r.type = value1.type; r.index = index; SSAInstruction move = new Monadic(sCregMove, value1); move.result = r; move.result.owner = move; addInstruction(move); exitSet[index] = r; }else{ exitSet[index] = value1; } } }
package org.jasig.portal; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Describes a published channel. * @author George Lindholm, ITServices, UBC * @version $Revision$ */ public class ChannelDefinition { private int id; private String chanFName; private String chanName; private String chanDesc; private String chanTitle; private String chanClass; private int chanTimeout; private int chanTypeId; private int chanPupblUsrId; private int chanApvlId; private Date chanPublDt; private Date chanApvlDt; private boolean chanEditable; private boolean chanHasHelp; private boolean chanHasAbout; private List parameters; /** * Constructs a channel definition. * @param id the channel definition ID */ public ChannelDefinition(int id) { this.id = id; this.chanTitle = ""; this.chanDesc = ""; this.chanClass = ""; this.parameters = new ArrayList(); } // Getter methods public int getId() { return id; } public String getFName() { return chanFName; } public String getName() { return chanName; } public String getDescription() { return chanDesc; } public String getTitle() { return chanTitle; } public String getJavaClass() { return chanClass; } public int getTimeout() { return chanTimeout; } public int getTypeId() { return chanTypeId; } public int getPublisherId() { return chanPupblUsrId; } public int getApproverId() { return chanApvlId; } public Date getPublishDate() { return chanPublDt; } public Date getApprovalDate() { return chanApvlDt;} public boolean isEditable() { return chanEditable; } public boolean hasHelp() { return chanHasHelp; } public boolean hasAbout() { return chanHasAbout; } public ChannelParameter[] getParameters() { return (ChannelParameter[])parameters.toArray(new ChannelParameter[0]); } // Setter methods public void setFName(String fname) {this.chanFName =fname; } public void setName(String name) {this.chanName = name; } public void setDescription(String descr) {this.chanDesc = descr; } public void setTitle(String title) {this.chanTitle = title; } public void setJavaClass(String javaClass) {this.chanClass = javaClass; } public void setTimeout(int timeout) {this.chanTimeout = timeout; } public void setTypeId(int typeId) {this.chanTypeId = typeId; } public void setPublisherId(int publisherId) {this.chanPupblUsrId = publisherId; } public void setApproverId(int approvalId) {this.chanApvlId = approvalId; } public void setPublishDate(Date publishDate) {this.chanPublDt = publishDate; } public void setApprovalDate(Date approvalDate) {this.chanApvlDt = approvalDate; } public void setEditable(boolean editable) {this.chanEditable = editable; } public void setHasHelp(boolean hasHelp) {this.chanHasHelp = hasHelp; } public void setHasAbout(boolean hasAbout) {this.chanHasAbout = hasAbout; } public void setParameters(ChannelParameter[] parameters) { this.parameters = Arrays.asList(parameters); }; public void addParameter(String name, String value, String override) { parameters.add(new ChannelParameter(name, value, override)); } /** * Minimum attributes a channel must have */ private Element getBase(Document doc, String idTag, String chanClass, boolean editable, boolean hasHelp, boolean hasAbout) { Element channel = doc.createElement("channel"); ((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(idTag, channel); channel.setAttribute("ID", idTag); channel.setAttribute("chanID", id + ""); channel.setAttribute("timeout", chanTimeout + ""); channel.setAttribute("name", chanName); channel.setAttribute("title", chanTitle); channel.setAttribute("fname", chanFName); channel.setAttribute("class", chanClass); channel.setAttribute("typeID", chanTypeId + ""); channel.setAttribute("editable", editable ? "true" : "false"); channel.setAttribute("hasHelp", hasHelp ? "true" : "false"); channel.setAttribute("hasAbout", hasAbout ? "true" : "false"); return channel; } private final Element nodeParameter(Document doc, String name, int value) { return nodeParameter(doc, name, Integer.toString(value)); } private final Element nodeParameter(Document doc, String name, String value) { Element parameter = doc.createElement("parameter"); parameter.setAttribute("name", name); parameter.setAttribute("value", value); return parameter; } private final void addParameters(Document doc, Element channel) { if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ChannelParameter cp = (ChannelParameter) parameters.get(i); Element parameter = nodeParameter(doc, cp.name, cp.value); if (cp.override) { parameter.setAttribute("override", "yes"); } channel.appendChild(parameter); } } } /** * Display a message where this channel should be */ public Element getDocument(Document doc, String idTag, String statusMsg, int errorId) { Element channel = getBase(doc, idTag, "org.jasig.portal.channels.CError", false, false, false); addParameters(doc, channel); channel.appendChild(nodeParameter(doc, "CErrorMessage", statusMsg)); channel.appendChild(nodeParameter(doc, "CErrorChanId", idTag)); channel.appendChild(nodeParameter(doc, "CErrorErrorId", errorId)); return channel; } /** * return an xml representation of this channel */ public Element getDocument(Document doc, String idTag) { Element channel = getBase(doc, idTag, chanClass, chanEditable, chanHasHelp, chanHasAbout); channel.setAttribute("description", chanDesc); addParameters(doc, channel); return channel; } /** * Is it time to reload me from the data store */ public boolean refreshMe() { return false; } /** * Describes a channel definition parameter * A channel can have zero or more parameters. */ protected class ChannelParameter { String name; String value; boolean override; String descr; public ChannelParameter(String name, String value, String override) { this(name, value, RDBMServices.dbFlag(override)); } public ChannelParameter(String name, String value, boolean override) { this.name = name; this.value = value; this.override = override; } // Getter methods public String getName() { return name; } public String getValue() { return value; } public boolean getOverride() { return override; } public String getDescription() {return descr; } // Setter methods public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public void setOverride(boolean override) { this.override = override; } public void setDescription(String descr) { this.descr = descr; } } }
package org.jasig.portal.tools; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import org.jasig.portal.RDBMServices; import org.jasig.portal.services.LogService; /** * Adjusts stored layouts in 2.1 database to work in 2.2+. * @author Susan Bramhall, susan.bramhall@yale.edu * @version $Revision$ */ public class DbConvert21 { public static void main(String[] args) { Statement stmt = null; RDBMServices.PreparedStatement stmtTest = null; RDBMServices.PreparedStatement testStructStmt = null; Statement modifyStmt = null; ResultSet rset = null; ResultSet rsetTest = null; Connection con = null; int updateCount = 0; // the query to select all the layouts that need to be adjusted String query = "select uul.USER_ID, uul.LAYOUT_ID, max(uls.struct_id)+100 new_struct_id, " + "init_struct_id new_child_id from up_layout_struct uls, up_user_layout uul " + "where uls.user_id=uul.user_id and uls.layout_id=uul.layout_id " + "group by uul.user_id, uul.layout_id, init_struct_id"; String testQuery = "select count(*) ct from up_layout_struct where type='root' and user_id= ? and layout_id=?"; String testNextStructId = "SELECT NEXT_STRUCT_ID FROM UP_USER where user_id=? "; try { con = RDBMServices.getConnection (); if (con == null) { System.err.println("Unable to get a database connection"); return; } if (RDBMServices.supportsTransactions) con.setAutoCommit(false); // Create the JDBC statement stmt = con.createStatement(); // Add CHAN_SECURE column to UP_CHANNEL if not already there ResultSet rsMeta = null; DatabaseMetaData dbMeta = con.getMetaData(); try { rsMeta = dbMeta.getColumns(null,null,"UP_CHANNEL","CHAN_SECURE"); if (!rsMeta.next()){ String alter = "ALTER TABLE UP_CHANNEL ADD (CHAN_SECURE VARCHAR(1) DEFAULT 'N')"; con.createStatement().execute(alter); System.out.println("Added CHAN_SECURE column to UP_CHANNEL table."); } else System.out.println("CHAN_SECURE column already exists in UP_CHANNEL table."); } catch (SQLException se) { System.err.println("Error attempting to add CHAN_SECURE column to UP_CHANNEL table"); se.printStackTrace(); } try { rsMeta = dbMeta.getColumns(null,null,"UP_ENTITY_CACHE_INVALIDATION","ENTITY_CACHE_ID"); if (!rsMeta.next()){ String alter = "ALTER TABLE UP_ENTITY_CACHE_INVALIDATION ADD (ENTITY_CACHE_ID NUMBER NOT NULL)"; con.createStatement().execute(alter); System.out.println("Added ENTITY_CACHE_ID column to UP_ENTITY_CACHE_INVALIDATION table."); } else System.out.println("ENTITY_CACHE_ID column already exists in UP_ENTITY_CACHE_INVALIDATION table."); } catch (SQLException se) { System.err.println("Error attempting to add ENTITY_CACHE_ID column to UP_ENTITY_CACHE_INVALIDATION table"); se.printStackTrace(); } finally { if (rsMeta !=null) rsMeta.close(); } // change stylesheet URIs to classpath reference for resource manager try { Statement ssModifyStmt = con.createStatement(); rset = stmt.executeQuery("SELECT SS_ID, SS_URI, SS_DESCRIPTION_URI FROM UP_SS_STRUCT "); String newSsUri, ssUri, ssDescUri, updateSsUri; while (rset.next()) { int ssId = rset.getInt(1); ssUri = rset.getString(2); if (ssUri.startsWith("stylesheets/")) { newSsUri = ssUri.substring("stylesheets/".length()); updateSsUri = "UPDATE UP_SS_STRUCT set SS_URI = '"+newSsUri+"' "+ "where SS_ID = "+ssId; ssModifyStmt.execute(updateSsUri); LogService.log(LogService.DEBUG,"DbConvert21 update: "+updateSsUri); } ssDescUri = rset.getString(3); if (ssDescUri.startsWith("stylesheets/")) { newSsUri = ssDescUri.substring("stylesheets/".length()); updateSsUri = "UPDATE UP_SS_STRUCT set SS_DESCRIPTION_URI = '"+newSsUri+"' "+ "where SS_ID = "+ssId; ssModifyStmt.execute(updateSsUri); LogService.log(LogService.DEBUG,"DbConvert21 update: "+updateSsUri); } } rset = stmt.executeQuery("SELECT SS_ID, SS_URI, SS_DESCRIPTION_URI FROM UP_SS_THEME "); while (rset.next()) { int ssId = rset.getInt(1); ssUri = rset.getString(2); if (ssUri.startsWith("stylesheets/")) { newSsUri = ssUri.substring("stylesheets/".length()); updateSsUri = "UPDATE UP_SS_THEME set SS_URI = '"+newSsUri+"' "+ "where SS_ID = "+ssId; ssModifyStmt.execute(updateSsUri); LogService.log(LogService.DEBUG,"DbConvert21 update: "+updateSsUri); } ssDescUri = rset.getString(3); if (ssDescUri.startsWith("stylesheets/")) { newSsUri = ssDescUri.substring("stylesheets/".length()); updateSsUri = "UPDATE UP_SS_THEME set SS_DESCRIPTION_URI = '"+newSsUri+"' "+ "where SS_ID = "+ssId; ssModifyStmt.execute(updateSsUri); LogService.log(LogService.DEBUG,"DbConvert21 update: "+updateSsUri); } } } catch (SQLException se) { System.err.println("Error updating stylesheet Uri"); se.printStackTrace(); } finally { if (rset!=null) rset.close(); System.out.println("stylesheet references updated."); } // update layouts to add new folder try { rset = stmt.executeQuery(query); try { // Create statements for modifications // for updating the layout modifyStmt = con.createStatement(); // to test if already modfied stmtTest = new RDBMServices.PreparedStatement(con, testQuery); // to test if need to increment next struct id for user testStructStmt = new RDBMServices.PreparedStatement(con, testNextStructId); // loop through returned results while (rset.next()) { int user_id = rset.getInt("USER_ID"); int layout_id = rset.getInt("LAYOUT_ID"); int new_struct_id = rset.getInt("new_struct_id"); int new_child_id = rset.getInt("new_child_id"); stmtTest.clearParameters(); stmtTest.setInt(1,user_id); stmtTest.setInt(2,layout_id); rsetTest = stmtTest.executeQuery(); if (rsetTest.next() && rsetTest.getInt("ct")>0) { System.err.println("DbConvert: root folder already exists. USER_ID " + user_id + ", LAYOUT_ID " + layout_id + " ignored"); } else { String insertString = "INSERT INTO UP_LAYOUT_STRUCT ( USER_ID, LAYOUT_ID, STRUCT_ID, "+ "NEXT_STRUCT_ID, CHLD_STRUCT_ID, NAME, TYPE, IMMUTABLE, UNREMOVABLE) VALUES ("+ user_id+", "+layout_id+", "+new_struct_id+", null, "+new_child_id+ ", 'Root Folder', 'root', 'N', 'Y')" ; modifyStmt.execute(insertString); // DEBUG LogService.log(LogService.DEBUG, "DbConvert inserted: " + insertString); String updateString = "UPDATE UP_USER_LAYOUT set INIT_STRUCT_ID="+new_struct_id+ " where user_id="+user_id + " and layout_id=" + layout_id; modifyStmt.execute(updateString); LogService.log(LogService.DEBUG, "DbConvert updated layout: " + updateString); testStructStmt.clearParameters(); testStructStmt.setInt(1,user_id); ResultSet testNext = testStructStmt.executeQuery(); int newNext = new_struct_id+1; if (testNext.next() && testNext.getInt(1)<=newNext){ updateString = "UPDATE UP_USER set NEXT_STRUCT_ID = " + newNext + " where user_id="+user_id ; modifyStmt.execute(updateString); LogService.log(LogService.DEBUG, "DbConvert updated next struct id : " + updateString); } LogService.log(LogService.DEBUG, "DbConvert updated: " + updateString); updateCount++; } } if (RDBMServices.supportsTransactions) con.commit(); } finally { stmt.close(); modifyStmt.close(); if (stmtTest != null) stmtTest.close(); } } catch (Exception e) { System.err.println("Error attempting to update layouts."); e.printStackTrace(); } finally { rset.close(); if (rsetTest!=null) rsetTest.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { RDBMServices.releaseConnection(con); } catch (Exception e) {} } System.out.println("DbConvert21 updated " + updateCount +" user layouts"); }//end main }