diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/test/org/apache/hadoop/ipc/TestIPC.java b/src/test/org/apache/hadoop/ipc/TestIPC.java
index 0a669dd28..43d8f1bd9 100644
--- a/src/test/org/apache/hadoop/ipc/TestIPC.java
+++ b/src/test/org/apache/hadoop/ipc/TestIPC.java
@@ -1,213 +1,213 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ipc;
import org.apache.commons.logging.*;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.LongWritable;
import java.util.Random;
import java.io.IOException;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
/** Unit tests for IPC. */
public class TestIPC extends TestCase {
public static final Log LOG =
LogFactory.getLog("org.apache.hadoop.ipc.TestIPC");
private static Configuration conf = new Configuration();
public TestIPC(String name) { super(name); }
private static final Random RANDOM = new Random();
private static final int PORT = 1234;
private static final String ADDRESS = "0.0.0.0";
private static class TestServer extends Server {
private boolean sleep;
public TestServer(String bindAddress, int port, int handlerCount, boolean sleep) {
super(bindAddress, port, LongWritable.class, handlerCount, conf);
this.setTimeout(1000);
this.sleep = sleep;
}
public Writable call(Writable param) throws IOException {
if (sleep) {
try {
Thread.sleep(RANDOM.nextInt(200)); // sleep a bit
} catch (InterruptedException e) {}
}
return param; // echo param as result
}
}
private static class SerialCaller extends Thread {
private Client client;
private int count;
private boolean failed;
public SerialCaller(Client client, int count) {
this.client = client;
this.count = count;
client.setTimeout(1000);
}
public void run() {
for (int i = 0; i < count; i++) {
try {
LongWritable param = new LongWritable(RANDOM.nextLong());
LongWritable value =
(LongWritable)client.call(param, new InetSocketAddress(PORT));
if (!param.equals(value)) {
LOG.fatal("Call failed!");
failed = true;
break;
}
} catch (Exception e) {
LOG.fatal("Caught: " + e);
failed = true;
}
}
}
}
private static class ParallelCaller extends Thread {
private Client client;
private int count;
private InetSocketAddress[] addresses;
private boolean failed;
public ParallelCaller(Client client, InetSocketAddress[] addresses,
int count) {
this.client = client;
this.addresses = addresses;
this.count = count;
client.setTimeout(1000);
}
public void run() {
for (int i = 0; i < count; i++) {
try {
Writable[] params = new Writable[addresses.length];
for (int j = 0; j < addresses.length; j++)
params[j] = new LongWritable(RANDOM.nextLong());
Writable[] values = client.call(params, addresses);
for (int j = 0; j < addresses.length; j++) {
if (!params[j].equals(values[j])) {
LOG.fatal("Call failed!");
failed = true;
break;
}
}
} catch (Exception e) {
LOG.fatal("Caught: " + e);
failed = true;
}
}
}
}
public void testSerial() throws Exception {
testSerial(3, false, 2, 5, 100);
}
public void testSerial(int handlerCount, boolean handlerSleep,
int clientCount, int callerCount, int callCount)
throws Exception {
Server server = new TestServer(ADDRESS, PORT, handlerCount, handlerSleep);
server.start();
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
clients[i] = new Client(LongWritable.class, conf);
}
SerialCaller[] callers = new SerialCaller[callerCount];
for (int i = 0; i < callerCount; i++) {
callers[i] = new SerialCaller(clients[i%clientCount], callCount);
callers[i].start();
}
for (int i = 0; i < callerCount; i++) {
callers[i].join();
assertFalse(callers[i].failed);
}
for (int i = 0; i < clientCount; i++) {
clients[i].stop();
}
server.stop();
}
public void testParallel() throws Exception {
testParallel(10, false, 2, 4, 2, 4, 100);
}
public void testParallel(int handlerCount, boolean handlerSleep,
int serverCount, int addressCount,
int clientCount, int callerCount, int callCount)
throws Exception {
Server[] servers = new Server[serverCount];
for (int i = 0; i < serverCount; i++) {
- servers[i] = new TestServer(ADDRESS, PORT+i, handlerCount, handlerSleep);
+ servers[i] = new TestServer(ADDRESS, PORT+i+1, handlerCount, handlerSleep);
servers[i].start();
}
InetSocketAddress[] addresses = new InetSocketAddress[addressCount];
for (int i = 0; i < addressCount; i++) {
- addresses[i] = new InetSocketAddress(PORT+(i%serverCount));
+ addresses[i] = new InetSocketAddress(PORT+1+(i%serverCount));
}
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
clients[i] = new Client(LongWritable.class, conf);
}
ParallelCaller[] callers = new ParallelCaller[callerCount];
for (int i = 0; i < callerCount; i++) {
callers[i] =
new ParallelCaller(clients[i%clientCount], addresses, callCount);
callers[i].start();
}
for (int i = 0; i < callerCount; i++) {
callers[i].join();
assertFalse(callers[i].failed);
}
for (int i = 0; i < clientCount; i++) {
clients[i].stop();
}
for (int i = 0; i < serverCount; i++) {
servers[i].stop();
}
}
public static void main(String[] args) throws Exception {
//new TestIPC("test").testSerial(5, false, 2, 10, 1000);
new TestIPC("test").testParallel(10, false, 2, 4, 2, 4, 1000);
}
}
| false | true |
public void testParallel(int handlerCount, boolean handlerSleep,
int serverCount, int addressCount,
int clientCount, int callerCount, int callCount)
throws Exception {
Server[] servers = new Server[serverCount];
for (int i = 0; i < serverCount; i++) {
servers[i] = new TestServer(ADDRESS, PORT+i, handlerCount, handlerSleep);
servers[i].start();
}
InetSocketAddress[] addresses = new InetSocketAddress[addressCount];
for (int i = 0; i < addressCount; i++) {
addresses[i] = new InetSocketAddress(PORT+(i%serverCount));
}
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
clients[i] = new Client(LongWritable.class, conf);
}
ParallelCaller[] callers = new ParallelCaller[callerCount];
for (int i = 0; i < callerCount; i++) {
callers[i] =
new ParallelCaller(clients[i%clientCount], addresses, callCount);
callers[i].start();
}
for (int i = 0; i < callerCount; i++) {
callers[i].join();
assertFalse(callers[i].failed);
}
for (int i = 0; i < clientCount; i++) {
clients[i].stop();
}
for (int i = 0; i < serverCount; i++) {
servers[i].stop();
}
}
|
public void testParallel(int handlerCount, boolean handlerSleep,
int serverCount, int addressCount,
int clientCount, int callerCount, int callCount)
throws Exception {
Server[] servers = new Server[serverCount];
for (int i = 0; i < serverCount; i++) {
servers[i] = new TestServer(ADDRESS, PORT+i+1, handlerCount, handlerSleep);
servers[i].start();
}
InetSocketAddress[] addresses = new InetSocketAddress[addressCount];
for (int i = 0; i < addressCount; i++) {
addresses[i] = new InetSocketAddress(PORT+1+(i%serverCount));
}
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
clients[i] = new Client(LongWritable.class, conf);
}
ParallelCaller[] callers = new ParallelCaller[callerCount];
for (int i = 0; i < callerCount; i++) {
callers[i] =
new ParallelCaller(clients[i%clientCount], addresses, callCount);
callers[i].start();
}
for (int i = 0; i < callerCount; i++) {
callers[i].join();
assertFalse(callers[i].failed);
}
for (int i = 0; i < clientCount; i++) {
clients[i].stop();
}
for (int i = 0; i < serverCount; i++) {
servers[i].stop();
}
}
|
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/TestCloseNoSave.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/TestCloseNoSave.java
index ae0b1a019..93ab7308d 100644
--- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/TestCloseNoSave.java
+++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/TestCloseNoSave.java
@@ -1,54 +1,56 @@
package org.eclipse.core.tests.resources.session;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
/**
* Tests closing a workspace without save.
*/
public class TestCloseNoSave extends WorkspaceSerializationTest {
/**
* Constructor for TestCloseNoSave.
*/
public TestCloseNoSave() {
super();
}
/**
* Constructor for TestCloseNoSave.
* @param name
*/
public TestCloseNoSave(String name) {
super(name);
}
public void test1() throws CoreException {
/* create some resource handles */
IProject project = workspace.getRoot().getProject(PROJECT);
project.create(getMonitor());
project.open(getMonitor());
IFolder folder = project.getFolder(FOLDER);
folder.create(true, true, getMonitor());
IFile file = folder.getFile(FILE);
file.create(getRandomContents(), true, getMonitor());
}
public void test2() throws CoreException {
/* projects should exist, but files shouldn't. Refresh local should bring in files */
IResource[] members = workspace.getRoot().members();
assertEquals("1.0", 1, members.length);
assertTrue("1.1", members[0].getType() == IResource.PROJECT);
IProject project = (IProject)members[0];
assertTrue("1.2", project.exists());
- assertEquals("1.3", 0, project.members().length);
+ members = project.members();
+ assertEquals("1.3", 1, members.length);
+ assertEquals("1.3a", ".project", members[0].getName());
IFolder folder = project.getFolder(FOLDER);
IFile file = folder.getFile(FILE);
assertTrue("1.4", !folder.exists());
assertTrue("1.5", !file.exists());
//opening the project does an automatic local refresh
project.open(null);
- assertEquals("2.0", 1, project.members().length);
+ assertEquals("2.0", 2, project.members().length);
assertTrue("2.1", folder.exists());
assertTrue("2.2", file.exists());
}
}
| false | true |
public void test2() throws CoreException {
/* projects should exist, but files shouldn't. Refresh local should bring in files */
IResource[] members = workspace.getRoot().members();
assertEquals("1.0", 1, members.length);
assertTrue("1.1", members[0].getType() == IResource.PROJECT);
IProject project = (IProject)members[0];
assertTrue("1.2", project.exists());
assertEquals("1.3", 0, project.members().length);
IFolder folder = project.getFolder(FOLDER);
IFile file = folder.getFile(FILE);
assertTrue("1.4", !folder.exists());
assertTrue("1.5", !file.exists());
//opening the project does an automatic local refresh
project.open(null);
assertEquals("2.0", 1, project.members().length);
assertTrue("2.1", folder.exists());
assertTrue("2.2", file.exists());
}
|
public void test2() throws CoreException {
/* projects should exist, but files shouldn't. Refresh local should bring in files */
IResource[] members = workspace.getRoot().members();
assertEquals("1.0", 1, members.length);
assertTrue("1.1", members[0].getType() == IResource.PROJECT);
IProject project = (IProject)members[0];
assertTrue("1.2", project.exists());
members = project.members();
assertEquals("1.3", 1, members.length);
assertEquals("1.3a", ".project", members[0].getName());
IFolder folder = project.getFolder(FOLDER);
IFile file = folder.getFile(FILE);
assertTrue("1.4", !folder.exists());
assertTrue("1.5", !file.exists());
//opening the project does an automatic local refresh
project.open(null);
assertEquals("2.0", 2, project.members().length);
assertTrue("2.1", folder.exists());
assertTrue("2.2", file.exists());
}
|
diff --git a/src/main/java/org/pa/boundless/bsp/ChunkReader.java b/src/main/java/org/pa/boundless/bsp/ChunkReader.java
index 7377b20..eaaa658 100644
--- a/src/main/java/org/pa/boundless/bsp/ChunkReader.java
+++ b/src/main/java/org/pa/boundless/bsp/ChunkReader.java
@@ -1,243 +1,245 @@
package org.pa.boundless.bsp;
import static org.apache.commons.lang3.Validate.isTrue;
import static org.apache.commons.lang3.Validate.notNull;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
/**
* A reader for types in the raw-package using reflection.
*
* @author palador
*
* @param <T>
* the chunk-type
*/
public class ChunkReader<T> {
private static final HashSet<Class<?>> VALID_FIELD_TYPES = new HashSet<>(
Arrays.asList((Class<?>) int.class, char.class, float.class,
byte.class));
private final Class<T> type;
private final int chunkLength;
private final ArrayList<FieldLoader> fieldLoaders = new ArrayList<>();
/**
* Creates a chunkreader for the specified type.
*
* @param chunkType
* the type to load, must not be <code>null</code>
* @throws IllegalArgumentException
* If <code>chunkType</code> is <code>null</code> or can't be
* read automatically.
*/
public ChunkReader(Class<T> chunkType) throws IllegalArgumentException {
type = notNull(chunkType);
try {
T dummy = chunkType.newInstance();
int chunkLen = 0;
// go through fields
for (Field field : chunkType.getFields()) {
int fieldMod = field.getModifiers();
Class<?> fieldType = field.getType();
// ignore static and non-public fields
if ((fieldMod & Modifier.STATIC) != 0
|| (fieldMod & Modifier.PUBLIC) == 0) {
continue;
}
if (fieldType.isArray()) {
isTrue((fieldMod & Modifier.FINAL) != 0,
"Array must be final: %s", field.getName());
// get and validate array-type and find out how many
// dimensions the array has
int dimensions = 0;
Class<?> arrayType = fieldType;
while (arrayType.isArray()) {
dimensions++;
arrayType = arrayType.getComponentType();
}
int[] dimensionsLengths = new int[dimensions];
isTrue(VALID_FIELD_TYPES.contains(arrayType),
"array-type of %s must not be %s", field.getName(),
arrayType.getName());
// get the current value to analyze
Object arrayValue = field.get(dummy);
notNull(arrayValue, "array-field must not be null: "
+ field.getName());
// find out how long each dimension is and increase chunkLen
+ int totalElementCount = 1;
for (int dim = 0; dim < dimensions; dim++) {
dimensionsLengths[dim] = Array.getLength(arrayValue);
- chunkLen += sizeof(arrayType) * dimensionsLengths[dim];
+ totalElementCount *= dimensionsLengths[dim];
arrayValue = Array.get(arrayValue, 0);
}
+ chunkLen += totalElementCount * sizeof(arrayType);
fieldLoaders.add(new ArrayFieldLoader(field, arrayType,
dimensionsLengths));
} else {
// not an array, field is simple
isTrue((fieldMod & Modifier.FINAL) == 0,
"Field must not be final: %s", field.getName());
isTrue(VALID_FIELD_TYPES.contains(fieldType),
"field-type of %s must not ne %s", field.getName(),
fieldType.getName());
chunkLen += sizeof(fieldType);
fieldLoaders.add(new SimpleFieldLoader(field));
}
}
chunkLength = chunkLen;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Type is not creatable or a field is not accessable: "
+ chunkType.getName(), e);
}
}
public int getChunkLength() {
return chunkLength;
}
public T loadChunk(ByteBuffer is) throws IOException {
T result;
try {
result = type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
for (FieldLoader fieldLoader : fieldLoaders) {
fieldLoader.loadField(is, result);
}
return result;
}
/**
* Returns the size of a primitive type in bytes. I know that chars are
* actually 2 bytes in java, but not in bsp-files.
*
* @param type
* @return
*/
private static int sizeof(Class<?> type) {
if (type == char.class || type == byte.class) {
return 1;
} else {
return 4;
}
}
/**
* Loads a value from an InputStream.
*
* @param is
* @param fieldType
* @return
* @throws IOException
*/
private static Object loadValue(ByteBuffer buf, Class<?> fieldType)
throws IOException {
Object value = null;
if (fieldType == byte.class) {
value = buf.get();
} else if (fieldType == char.class) {
value = (char) buf.get();
} else if (fieldType == int.class) {
value = buf.getInt();
} else if (fieldType == float.class) {
value = buf.getFloat();
}
return value;
}
private static interface FieldLoader {
void loadField(ByteBuffer buf, Object obj) throws IOException;
}
private static class SimpleFieldLoader implements FieldLoader {
private final Field field;
SimpleFieldLoader(Field field) {
this.field = field;
}
@Override
public void loadField(ByteBuffer buf, Object obj) throws IOException {
try {
field.set(obj, loadValue(buf, field.getType()));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
private static class ArrayFieldLoader implements FieldLoader {
private final Field field;
private final Class<?> arrayType;
private final int[] dimensionLengths;
private final int[] blockLengths;
ArrayFieldLoader(Field field, Class<?> arrayType, int[] dimensionLengths) {
this.field = field;
this.arrayType = arrayType;
this.dimensionLengths = dimensionLengths;
blockLengths = new int[dimensionLengths.length];
for (int dim = dimensionLengths.length - 1; dim >= 0; dim--) {
blockLengths[dim] = dimensionLengths[dim];
if (dim < dimensionLengths.length - 1) {
blockLengths[dim] *= blockLengths[dim + 1];
}
}
}
@Override
public void loadField(ByteBuffer buf, Object obj) throws IOException {
Object array;
try {
array = field.get(obj);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
int totalElements = 1;
for (int dim = 0; dim < dimensionLengths.length; dim++) {
totalElements *= dimensionLengths[dim];
}
for (int element = 0; element < totalElements; element++) {
Object primitiveArray = array;
for (int dim = 0; dim < dimensionLengths.length - 1; dim++) {
// fancy: convert element index to index of the current
// dimension
int index = (element / blockLengths[dim + 1])
% dimensionLengths[dim];
primitiveArray = Array.get(primitiveArray, index);
}
Object elementValue = loadValue(buf, arrayType);
Array.set(primitiveArray, element
% dimensionLengths[dimensionLengths.length - 1],
elementValue);
}
}
}
}
| false | true |
public ChunkReader(Class<T> chunkType) throws IllegalArgumentException {
type = notNull(chunkType);
try {
T dummy = chunkType.newInstance();
int chunkLen = 0;
// go through fields
for (Field field : chunkType.getFields()) {
int fieldMod = field.getModifiers();
Class<?> fieldType = field.getType();
// ignore static and non-public fields
if ((fieldMod & Modifier.STATIC) != 0
|| (fieldMod & Modifier.PUBLIC) == 0) {
continue;
}
if (fieldType.isArray()) {
isTrue((fieldMod & Modifier.FINAL) != 0,
"Array must be final: %s", field.getName());
// get and validate array-type and find out how many
// dimensions the array has
int dimensions = 0;
Class<?> arrayType = fieldType;
while (arrayType.isArray()) {
dimensions++;
arrayType = arrayType.getComponentType();
}
int[] dimensionsLengths = new int[dimensions];
isTrue(VALID_FIELD_TYPES.contains(arrayType),
"array-type of %s must not be %s", field.getName(),
arrayType.getName());
// get the current value to analyze
Object arrayValue = field.get(dummy);
notNull(arrayValue, "array-field must not be null: "
+ field.getName());
// find out how long each dimension is and increase chunkLen
for (int dim = 0; dim < dimensions; dim++) {
dimensionsLengths[dim] = Array.getLength(arrayValue);
chunkLen += sizeof(arrayType) * dimensionsLengths[dim];
arrayValue = Array.get(arrayValue, 0);
}
fieldLoaders.add(new ArrayFieldLoader(field, arrayType,
dimensionsLengths));
} else {
// not an array, field is simple
isTrue((fieldMod & Modifier.FINAL) == 0,
"Field must not be final: %s", field.getName());
isTrue(VALID_FIELD_TYPES.contains(fieldType),
"field-type of %s must not ne %s", field.getName(),
fieldType.getName());
chunkLen += sizeof(fieldType);
fieldLoaders.add(new SimpleFieldLoader(field));
}
}
chunkLength = chunkLen;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Type is not creatable or a field is not accessable: "
+ chunkType.getName(), e);
}
}
|
public ChunkReader(Class<T> chunkType) throws IllegalArgumentException {
type = notNull(chunkType);
try {
T dummy = chunkType.newInstance();
int chunkLen = 0;
// go through fields
for (Field field : chunkType.getFields()) {
int fieldMod = field.getModifiers();
Class<?> fieldType = field.getType();
// ignore static and non-public fields
if ((fieldMod & Modifier.STATIC) != 0
|| (fieldMod & Modifier.PUBLIC) == 0) {
continue;
}
if (fieldType.isArray()) {
isTrue((fieldMod & Modifier.FINAL) != 0,
"Array must be final: %s", field.getName());
// get and validate array-type and find out how many
// dimensions the array has
int dimensions = 0;
Class<?> arrayType = fieldType;
while (arrayType.isArray()) {
dimensions++;
arrayType = arrayType.getComponentType();
}
int[] dimensionsLengths = new int[dimensions];
isTrue(VALID_FIELD_TYPES.contains(arrayType),
"array-type of %s must not be %s", field.getName(),
arrayType.getName());
// get the current value to analyze
Object arrayValue = field.get(dummy);
notNull(arrayValue, "array-field must not be null: "
+ field.getName());
// find out how long each dimension is and increase chunkLen
int totalElementCount = 1;
for (int dim = 0; dim < dimensions; dim++) {
dimensionsLengths[dim] = Array.getLength(arrayValue);
totalElementCount *= dimensionsLengths[dim];
arrayValue = Array.get(arrayValue, 0);
}
chunkLen += totalElementCount * sizeof(arrayType);
fieldLoaders.add(new ArrayFieldLoader(field, arrayType,
dimensionsLengths));
} else {
// not an array, field is simple
isTrue((fieldMod & Modifier.FINAL) == 0,
"Field must not be final: %s", field.getName());
isTrue(VALID_FIELD_TYPES.contains(fieldType),
"field-type of %s must not ne %s", field.getName(),
fieldType.getName());
chunkLen += sizeof(fieldType);
fieldLoaders.add(new SimpleFieldLoader(field));
}
}
chunkLength = chunkLen;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Type is not creatable or a field is not accessable: "
+ chunkType.getName(), e);
}
}
|
diff --git a/src/SigmaEC/evaluate/ObjectiveViewer.java b/src/SigmaEC/evaluate/ObjectiveViewer.java
index 4c457d1..f8a8c21 100644
--- a/src/SigmaEC/evaluate/ObjectiveViewer.java
+++ b/src/SigmaEC/evaluate/ObjectiveViewer.java
@@ -1,47 +1,47 @@
package SigmaEC.evaluate;
import SigmaEC.represent.DoubleVectorIndividual;
import SigmaEC.represent.SimpleDoubleVectorIndividual;
import SigmaEC.util.IDoublePoint;
import SigmaEC.util.Misc;
import java.io.IOException;
import java.io.Writer;
/**
* Takes an objective function over R^2 and samples it along a grid to produce
* a matrix suitable for visualization.
*
* @author Eric 'Siggy' Scott
*/
public class ObjectiveViewer
{
public static <T extends ObjectiveFunction<DoubleVectorIndividual> & Dimensioned>
void viewObjective(T objective, double granularity, IDoublePoint[] bounds, Writer outputDestination) throws IllegalArgumentException, IOException
{
if (objective == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: objective is null.");
if (objective.getNumDimensions() != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of objective is %d, but must be 2.", objective.getNumDimensions()));
if (granularity <= 0)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: granularity is not positive.");
if (bounds == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds is null.");
if (bounds.length != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of bounds is %d, but must be 2.", bounds.length));
if (Misc.containsNulls(bounds))
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds contains null values.");
if (outputDestination == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: outputDestination is null.");
for (double x = bounds[0].x; x <= bounds[0].y; x += granularity)
{
for (double y = bounds[1].x; y <= bounds[1].y; y += granularity)
{
SimpleDoubleVectorIndividual ind = new SimpleDoubleVectorIndividual(new double[] { x, y });
double fitness = objective.fitness(ind);
- outputDestination.write(String.format("%d, %d, %f", x, y, fitness));
+ outputDestination.write(String.format("%f, %f, %f\n", x, y, fitness));
}
}
outputDestination.flush();
}
}
| true | true |
public static <T extends ObjectiveFunction<DoubleVectorIndividual> & Dimensioned>
void viewObjective(T objective, double granularity, IDoublePoint[] bounds, Writer outputDestination) throws IllegalArgumentException, IOException
{
if (objective == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: objective is null.");
if (objective.getNumDimensions() != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of objective is %d, but must be 2.", objective.getNumDimensions()));
if (granularity <= 0)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: granularity is not positive.");
if (bounds == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds is null.");
if (bounds.length != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of bounds is %d, but must be 2.", bounds.length));
if (Misc.containsNulls(bounds))
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds contains null values.");
if (outputDestination == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: outputDestination is null.");
for (double x = bounds[0].x; x <= bounds[0].y; x += granularity)
{
for (double y = bounds[1].x; y <= bounds[1].y; y += granularity)
{
SimpleDoubleVectorIndividual ind = new SimpleDoubleVectorIndividual(new double[] { x, y });
double fitness = objective.fitness(ind);
outputDestination.write(String.format("%d, %d, %f", x, y, fitness));
}
}
outputDestination.flush();
}
|
public static <T extends ObjectiveFunction<DoubleVectorIndividual> & Dimensioned>
void viewObjective(T objective, double granularity, IDoublePoint[] bounds, Writer outputDestination) throws IllegalArgumentException, IOException
{
if (objective == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: objective is null.");
if (objective.getNumDimensions() != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of objective is %d, but must be 2.", objective.getNumDimensions()));
if (granularity <= 0)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: granularity is not positive.");
if (bounds == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds is null.");
if (bounds.length != 2)
throw new IllegalArgumentException(String.format("ObjectiveViewer.viewObjective: dimensionality of bounds is %d, but must be 2.", bounds.length));
if (Misc.containsNulls(bounds))
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: bounds contains null values.");
if (outputDestination == null)
throw new IllegalArgumentException("ObjectiveViewer.viewObjective: outputDestination is null.");
for (double x = bounds[0].x; x <= bounds[0].y; x += granularity)
{
for (double y = bounds[1].x; y <= bounds[1].y; y += granularity)
{
SimpleDoubleVectorIndividual ind = new SimpleDoubleVectorIndividual(new double[] { x, y });
double fitness = objective.fitness(ind);
outputDestination.write(String.format("%f, %f, %f\n", x, y, fitness));
}
}
outputDestination.flush();
}
|
diff --git a/jython/src/org/python/modules/operator.java b/jython/src/org/python/modules/operator.java
index 7d9e3480..542b8f34 100644
--- a/jython/src/org/python/modules/operator.java
+++ b/jython/src/org/python/modules/operator.java
@@ -1,396 +1,396 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.modules;
import org.python.core.*;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
class OperatorFunctions extends PyBuiltinFunctionSet
{
public OperatorFunctions(String name, int index, int argcount) {
this(name, index, argcount, argcount);
}
public OperatorFunctions(String name, int index, int minargs, int maxargs)
{
super(name, index, minargs, maxargs);
}
public PyObject __call__(PyObject arg1) {
switch (index) {
case 10: return arg1.__abs__();
case 11: return arg1.__invert__();
case 12: return arg1.__neg__();
case 13: return arg1.__not__();
case 14: return arg1.__pos__();
case 15: return Py.newBoolean(arg1.__nonzero__());
case 16: return Py.newBoolean(arg1.isCallable());
case 17: return Py.newBoolean(arg1.isMappingType());
case 18: return Py.newBoolean(arg1.isNumberType());
case 19: return Py.newBoolean(arg1.isSequenceType());
case 32: return arg1.__invert__();
case 52: return arg1.__index__();
default:
throw info.unexpectedCall(1, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2) {
switch (index) {
case 0: return arg1._add(arg2);
case 1: return arg1._and(arg2);
case 2: return arg1._div(arg2);
case 3: return arg1._lshift(arg2);
case 4: return arg1._mod(arg2);
case 5: return arg1._mul(arg2);
case 6: return arg1._or(arg2);
case 7: return arg1._rshift(arg2);
case 8: return arg1._sub(arg2);
case 9: return arg1._xor(arg2);
case 20: return Py.newBoolean(arg1.__contains__(arg2));
case 21:
arg1.__delitem__(arg2);
return Py.None;
case 23: return arg1.__getitem__(arg2);
case 27: return arg1._ge(arg2);
case 28: return arg1._le(arg2);
case 29: return arg1._eq(arg2);
case 30: return arg1._floordiv(arg2);
case 31: return arg1._gt(arg2);
case 33: return arg1._lt(arg2);
case 34: return arg1._ne(arg2);
case 35: return arg1._truediv(arg2);
case 36: return arg1._pow(arg2);
case 37: return arg1._is(arg2);
case 38: return arg1._isnot(arg2);
case 39: return arg1._iadd(arg2);
case 40: return arg1._iand(arg2);
case 41: return arg1._idiv(arg2);
case 42: return arg1._ifloordiv(arg2);
case 43: return arg1._ilshift(arg2);
case 44: return arg1._imod(arg2);
case 45: return arg1._imul(arg2);
case 46: return arg1._ior(arg2);
case 47: return arg1._ipow(arg2);
case 48: return arg1._irshift(arg2);
case 49: return arg1._isub(arg2);
case 50: return arg1._itruediv(arg2);
case 51: return arg1._ixor(arg2);
default:
throw info.unexpectedCall(2, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
switch (index) {
case 22: arg1.__delslice__(arg2.__index__(), arg3.__index__()); return Py.None;
case 24: return arg1.__getslice__(arg2.__index__(), arg3.__index__());
case 25: arg1.__setitem__(arg2, arg3); return Py.None;
default:
throw info.unexpectedCall(3, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3,
PyObject arg4)
{
switch (index) {
case 26:
arg1.__setslice__(arg2.__index__(), arg3.__index__(), arg4);
return Py.None;
default:
throw info.unexpectedCall(4, false);
}
}
}
public class operator implements ClassDictInit
{
public static PyString __doc__ = new PyString(
"Operator interface.\n"+
"\n"+
"This module exports a set of functions implemented in C "+
"corresponding\n"+
"to the intrinsic operators of Python. For example, "+
"operator.add(x, y)\n"+
"is equivalent to the expression x+y. The function names "+
"are those\n"+
"used for special class methods; variants without leading "+
"and trailing\n"+
"'__' are also provided for convenience.\n"
);
public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
- dict.__setitem__("__index__", new OperatorFunctions("__ixor__", 52, 1));
- dict.__setitem__("index", new OperatorFunctions("ixor", 52, 1));
+ dict.__setitem__("__index__", new OperatorFunctions("__index__", 52, 1));
+ dict.__setitem__("index", new OperatorFunctions("index", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
public static int countOf(PyObject seq, PyObject item) {
int count = 0;
for (PyObject tmp : seq.asIterable()) {
if (item._eq(tmp).__nonzero__()) {
count++;
}
}
return count;
}
public static int indexOf(PyObject seq, PyObject item) {
int i = 0;
PyObject iter = seq.__iter__();
for (PyObject tmp = null; (tmp = iter.__iternext__()) != null; i++) {
if (item._eq(tmp).__nonzero__()) {
return i;
}
}
throw Py.ValueError("sequence.index(x): x not in list");
}
/**
* The attrgetter type.
*/
// XXX: not subclassable
@ExposedType(name = "operator.attrgetter")
static class PyAttrGetter extends PyObject {
public static final PyType TYPE = PyType.fromClass(PyAttrGetter.class);
public PyObject[] attrs;
public PyAttrGetter(PyObject[] attrs) {
this.attrs = attrs;
}
@ExposedNew
final static PyObject attrgetter___new__(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("attrgetter", args, keywords, "attr");
ap.noKeywords();
ap.getPyObject(0);
return new PyAttrGetter(args);
}
@Override
public PyObject __call__(PyObject[] args, String[] keywords) {
return attrgetter___call__(args, keywords);
}
@ExposedMethod
final PyObject attrgetter___call__(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("attrgetter", args, Py.NoKeywords, "obj");
PyObject obj = ap.getPyObject(0);
if (attrs.length == 1) {
return getattr(obj, attrs[0]);
}
PyObject[] result = new PyObject[attrs.length];
int i = 0;
for (PyObject attr : attrs) {
result[i++] = getattr(obj, attr);
}
return new PyTuple(result);
}
private PyObject getattr(PyObject obj, PyObject name) {
// XXX: We should probably have a PyObject.__getattr__(PyObject) that does
// this. This is different than __builtin__.getattr (in how it handles
// exceptions)
String nameStr;
if (name instanceof PyUnicode) {
nameStr = ((PyUnicode)name).encode();
} else if (name instanceof PyString) {
nameStr = name.asString();
} else {
throw Py.TypeError(String.format("attribute name must be string, not '%.200s'",
name.getType().fastGetName()));
}
return obj.__getattr__(nameStr.intern());
}
}
/**
* The itemgetter type.
*/
// XXX: not subclassable
@ExposedType(name = "operator.itemgetter")
static class PyItemGetter extends PyObject {
public static final PyType TYPE = PyType.fromClass(PyItemGetter.class);
public PyObject[] items;
public PyItemGetter(PyObject[] items) {
this.items = items;
}
@ExposedNew
final static PyObject itemgetter___new__(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("itemgetter", args, keywords, "attr");
ap.noKeywords();
ap.getPyObject(0);
return new PyItemGetter(args);
}
@Override
public PyObject __call__(PyObject[] args, String[] keywords) {
return itemgetter___call__(args, keywords);
}
@ExposedMethod
final PyObject itemgetter___call__(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("itemgetter", args, Py.NoKeywords, "obj");
PyObject obj = ap.getPyObject(0);
if (items.length == 1) {
return obj.__getitem__(items[0]);
}
PyObject[] result = new PyObject[items.length];
int i = 0;
for (PyObject item : items) {
result[i++] = obj.__getitem__(item);
}
return new PyTuple(result);
}
}
}
| true | true |
public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
dict.__setitem__("__index__", new OperatorFunctions("__ixor__", 52, 1));
dict.__setitem__("index", new OperatorFunctions("ixor", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
|
public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
dict.__setitem__("__index__", new OperatorFunctions("__index__", 52, 1));
dict.__setitem__("index", new OperatorFunctions("index", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
|
diff --git a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java
index c18dd66391..0edec57b05 100644
--- a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java
+++ b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java
@@ -1,48 +1,48 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.openhosting;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.Constants.PROPERTY_ENDPOINT;
import static org.jclouds.Constants.PROPERTY_ISO3166_CODES;
import java.util.Properties;
import org.jclouds.elasticstack.ElasticStackPropertiesBuilder;
/**
*
* @author Adrian Cole
*/
public class OpenHostingEast1PropertiesBuilder extends ElasticStackPropertiesBuilder {
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_ISO3166_CODES, "US-VA");
properties.setProperty(PROPERTY_ENDPOINT, "https://api.east1.openhosting.com");
- properties.setProperty(PROPERTY_API_VERSION, "1.0");
+ properties.setProperty(PROPERTY_API_VERSION, "2.0");
return properties;
}
public OpenHostingEast1PropertiesBuilder(Properties properties) {
super(properties);
}
}
| true | true |
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_ISO3166_CODES, "US-VA");
properties.setProperty(PROPERTY_ENDPOINT, "https://api.east1.openhosting.com");
properties.setProperty(PROPERTY_API_VERSION, "1.0");
return properties;
}
|
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_ISO3166_CODES, "US-VA");
properties.setProperty(PROPERTY_ENDPOINT, "https://api.east1.openhosting.com");
properties.setProperty(PROPERTY_API_VERSION, "2.0");
return properties;
}
|
diff --git a/src/main/java/clcert/Login.java b/src/main/java/clcert/Login.java
index 2106798..1648777 100644
--- a/src/main/java/clcert/Login.java
+++ b/src/main/java/clcert/Login.java
@@ -1,56 +1,58 @@
package clcert;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private Configuration config = null;
public Login() {
super();
try {
config = new PropertiesConfiguration("app.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("org.sqlite.JDBC");
Connection conexion = DriverManager.getConnection(config.getString("JDBC.connectionURL"));
Statement statement = conexion.createStatement();
String query = "select * from usuarios where username='" + username + "' and password = '" + password + "'";
ResultSet resultado = statement.executeQuery(query);
int numFilas = 0;
while (resultado.next())
numFilas++;
statement.close();
conexion.close();
if (numFilas > 0) {
response.addCookie(new Cookie("userIP", request.getRemoteAddr()));
response.addCookie(new Cookie("userHost", request.getRemoteHost()));
response.sendRedirect("saludos.jsp");
+ } else {
+ response.sendRedirect("login.jsp?notFoundError=1");
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
| true | true |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("org.sqlite.JDBC");
Connection conexion = DriverManager.getConnection(config.getString("JDBC.connectionURL"));
Statement statement = conexion.createStatement();
String query = "select * from usuarios where username='" + username + "' and password = '" + password + "'";
ResultSet resultado = statement.executeQuery(query);
int numFilas = 0;
while (resultado.next())
numFilas++;
statement.close();
conexion.close();
if (numFilas > 0) {
response.addCookie(new Cookie("userIP", request.getRemoteAddr()));
response.addCookie(new Cookie("userHost", request.getRemoteHost()));
response.sendRedirect("saludos.jsp");
}
} catch (Exception e) {
throw new ServletException(e);
}
}
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("org.sqlite.JDBC");
Connection conexion = DriverManager.getConnection(config.getString("JDBC.connectionURL"));
Statement statement = conexion.createStatement();
String query = "select * from usuarios where username='" + username + "' and password = '" + password + "'";
ResultSet resultado = statement.executeQuery(query);
int numFilas = 0;
while (resultado.next())
numFilas++;
statement.close();
conexion.close();
if (numFilas > 0) {
response.addCookie(new Cookie("userIP", request.getRemoteAddr()));
response.addCookie(new Cookie("userHost", request.getRemoteHost()));
response.sendRedirect("saludos.jsp");
} else {
response.sendRedirect("login.jsp?notFoundError=1");
}
} catch (Exception e) {
throw new ServletException(e);
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
index 09270de1f..48bf85f09 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
@@ -1,1057 +1,1057 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.Utilities;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import net.aufdemrand.denizen.utilities.depends.WorldGuardUtilities;
import net.aufdemrand.denizen.utilities.entity.Rotation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.World;
import org.bukkit.block.Sign;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dLocation extends org.bukkit.Location implements dObject {
// This pattern correctly reads both 0.9 and 0.8 notables
final static Pattern notablePattern =
Pattern.compile("(\\w+)[;,]((-?\\d+\\.?\\d*,){3,5}\\w+)",
Pattern.CASE_INSENSITIVE);
/////////////////////
// STATIC METHODS
/////////////////
public static Map<String, dLocation> uniqueObjects = new HashMap<String, dLocation>();
public static boolean isSaved(String id) {
return uniqueObjects.containsKey(id.toUpperCase());
}
public static boolean isSaved(dLocation location) {
return uniqueObjects.containsValue(location);
}
public static boolean isSaved(Location location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet())
if (i.getValue() == location) return true;
return uniqueObjects.containsValue(location);
}
public static dLocation getSaved(String id) {
if (uniqueObjects.containsKey(id.toUpperCase()))
return uniqueObjects.get(id.toUpperCase());
else return null;
}
public static String getSaved(dLocation location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet()) {
if (i.getValue().getBlockX() != location.getBlockX()) continue;
if (i.getValue().getBlockY() != location.getBlockY()) continue;
if (i.getValue().getBlockZ() != location.getBlockZ()) continue;
if (!i.getValue().getWorld().getName().equals(location.getWorld().getName())) continue;
return i.getKey();
}
return null;
}
public static String getSaved(Location location) {
dLocation dLoc = new dLocation(location);
return getSaved(dLoc);
}
public static void saveAs(dLocation location, String id) {
if (location == null) return;
uniqueObjects.put(id.toUpperCase(), location);
}
public static void remove(String id) {
uniqueObjects.remove(id.toUpperCase());
}
/*
* Called on server startup or /denizen reload locations. Should probably not be called manually.
*/
public static void _recallLocations() {
List<String> loclist = DenizenAPI.getCurrentInstance().getSaves().getStringList("dScript.Locations");
uniqueObjects.clear();
for (String location : loclist) {
Matcher m = notablePattern.matcher(location);
if (m.matches()) {
String id = m.group(1);
dLocation loc = valueOf(m.group(2));
uniqueObjects.put(id, loc);
}
}
}
/*
* Called by Denizen internally on a server shutdown or /denizen save. Should probably
* not be called manually.
*/
public static void _saveLocations() {
List<String> loclist = new ArrayList<String>();
for (Map.Entry<String, dLocation> entry : uniqueObjects.entrySet())
// Save locations in the horizontal centers of blocks
loclist.add(entry.getKey() + ";"
+ (entry.getValue().getBlockX() + 0.5)
+ "," + entry.getValue().getBlockY()
+ "," + (entry.getValue().getBlockZ() + 0.5)
+ "," + entry.getValue().getYaw()
+ "," + entry.getValue().getPitch()
+ "," + entry.getValue().getWorld().getName());
DenizenAPI.getCurrentInstance().getSaves().set("dScript.Locations", loclist);
}
//////////////////
// OBJECT FETCHER
////////////////
/**
* Gets a Location Object from a string form of id,x,y,z,world
* or a dScript argument (location:)x,y,z,world. If including an Id,
* this location will persist and can be recalled at any time.
*
* @param string the string or dScript argument String
* @return a Location, or null if incorrectly formatted
*
*/
@ObjectFetcher("l")
public static dLocation valueOf(String string) {
if (string == null) return null;
////////
// Match @object format for saved dLocations
Matcher m;
final Pattern item_by_saved = Pattern.compile("(l@)(.+)");
m = item_by_saved.matcher(string);
if (m.matches() && isSaved(m.group(2)))
return getSaved(m.group(2));
////////
// Match location formats
// Split values
String[] split = string.replace("l@", "").split(",");
if (split.length == 4)
// If 4 values, standard dScript location format
// x,y,z,world
try {
return new dLocation(Bukkit.getWorld(split[3]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]));
} catch(Exception e) {
return null;
}
else if (split.length == 6)
// If 6 values, location with pitch/yaw
// x,y,z,yaw,pitch,world
try
{ return new dLocation(Bukkit.getWorld(split[5]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]),
Float.valueOf(split[3]),
Float.valueOf(split[4]));
} catch(Exception e) {
return null;
}
dB.log("valueOf dLocation returning null: " + string);
return null;
}
public static boolean matches(String string) {
final Pattern location_by_saved = Pattern.compile("(l@)(.+)");
Matcher m = location_by_saved.matcher(string);
if (m.matches())
return true;
final Pattern location =
Pattern.compile("(-?\\d+\\.?\\d*,){3,5}\\w+",
Pattern.CASE_INSENSITIVE);
m = location.matcher(string);
return m.matches();
}
/**
* Turns a Bukkit Location into a Location, which has some helpful methods
* for working with dScript.
*
* @param location the Bukkit Location to reference
*/
public dLocation(Location location) {
// Just save the yaw and pitch as they are; don't check if they are
// higher than 0, because Minecraft yaws are weird and can have
// negative values
super(location.getWorld(), location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch());
}
/**
* Turns a world and coordinates into a Location, which has some helpful methods
* for working with dScript. If working with temporary locations, this is
* a much better method to use than {@link #dLocation(org.bukkit.World, double, double, double)}.
*
* @param world the world in which the location resides
* @param x x-coordinate of the location
* @param y y-coordinate of the location
* @param z z-coordinate of the location
*
*/
public dLocation(World world, double x, double y, double z) {
super(world, x, y, z);
}
public dLocation(World world, double x, double y, double z, float yaw, float pitch) {
super(world, x, y, z, pitch, yaw);
}
@Override
public void setPitch(float pitch) {
super.setPitch(pitch);
}
@Override
public void setYaw(float yaw) {
super.setYaw(yaw);
}
public dLocation rememberAs(String id) {
dLocation.saveAs(this, id);
return this;
}
String prefix = "Location";
@Override
public String getObjectType() {
return "Location";
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public dLocation setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (isSaved(this) ? "<G>" + prefix + "='<A>" + getSaved(this) + "(<Y>" + identify()+ "<A>)<G>' "
: "<G>" + prefix + "='<Y>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
return isSaved(this);
}
@Override
public String identify() {
if (isSaved(this))
return "l@" + getSaved(this);
else if (getYaw() != 0.0 && getPitch() != 0.0) return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getPitch() + "," + getYaw() + "," + getWorld().getName();
else return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getWorld().getName();
}
@Override
public String toString() {
return identify();
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
/////////////////////
// BLOCK ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block above this location.
// -->
if (attribute.startsWith("above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block below this location.
// -->
if (attribute.startsWith("below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block this location is on,
// i.e. returns a location without decimals or direction.
// -->
if (attribute.startsWith("block")) {
return new dLocation(getWorld(), getBlockX(), getBlockY(), getBlockZ())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the highest solid block at the location.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("material"))
- return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2));
+ return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation's block coordinates.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("simple.formatted"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple version of the dLocation's block coordinates.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
/////////////////////
// DIRECTION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// ENTITY AND BLOCK LIST ATTRIBUTES
/////////////////
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
/////////////////////
// MATHEMATICAL ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
/////////////////////
// WORLDGUARD ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the location is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the location is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
}
| true | true |
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
/////////////////////
// BLOCK ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block above this location.
// -->
if (attribute.startsWith("above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block below this location.
// -->
if (attribute.startsWith("below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block this location is on,
// i.e. returns a location without decimals or direction.
// -->
if (attribute.startsWith("block")) {
return new dLocation(getWorld(), getBlockX(), getBlockY(), getBlockZ())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the highest solid block at the location.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("material"))
return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation's block coordinates.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("simple.formatted"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple version of the dLocation's block coordinates.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
/////////////////////
// DIRECTION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// ENTITY AND BLOCK LIST ATTRIBUTES
/////////////////
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
/////////////////////
// MATHEMATICAL ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
/////////////////////
// WORLDGUARD ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the location is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the location is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
|
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
/////////////////////
// BLOCK ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block above this location.
// -->
if (attribute.startsWith("above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location one block below this location.
// -->
if (attribute.startsWith("below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block this location is on,
// i.e. returns a location without decimals or direction.
// -->
if (attribute.startsWith("block")) {
return new dLocation(getWorld(), getBlockX(), getBlockY(), getBlockZ())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the highest solid block at the location.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("material"))
return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation's block coordinates.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("simple.formatted"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple version of the dLocation's block coordinates.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
/////////////////////
// DIRECTION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// ENTITY AND BLOCK LIST ATTRIBUTES
/////////////////
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
/////////////////////
// MATHEMATICAL ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
/////////////////////
// WORLDGUARD ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the location is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the location is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
|
diff --git a/src/com/stormdev/minigamez/editor/CustomGameCreator.java b/src/com/stormdev/minigamez/editor/CustomGameCreator.java
index 685ca37..43a2011 100644
--- a/src/com/stormdev/minigamez/editor/CustomGameCreator.java
+++ b/src/com/stormdev/minigamez/editor/CustomGameCreator.java
@@ -1,18 +1,12 @@
package com.stormdev.minigamez.editor;
import java.io.IOException;
import java.io.InputStream;
public class CustomGameCreator {
public static void main(String[] args) {
- InputStream stream = CustomGameCreator.class.getResourceAsStream("plugin.yml"); //Make sure resource is copied to jar on export
- try {
- stream.close();
- } catch (IOException e) {
- //Do nothing
- }
System.out.println("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! ");
return;
}
}
| true | true |
public static void main(String[] args) {
InputStream stream = CustomGameCreator.class.getResourceAsStream("plugin.yml"); //Make sure resource is copied to jar on export
try {
stream.close();
} catch (IOException e) {
//Do nothing
}
System.out.println("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! ");
return;
}
|
public static void main(String[] args) {
System.out.println("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! ");
return;
}
|
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
index 725a50b46..24996b4d7 100644
--- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
+++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
@@ -1,220 +1,221 @@
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.internal.mapping;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.mapping.*;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.tests.resources.ResourceTest;
/**
* Tests for change validation
*/
public class ChangeValidationTest extends ResourceTest {
private IResourceChangeDescriptionFactory factory;
private IProject project;
public static Test suite() {
return new TestSuite(ChangeValidationTest.class);
}
private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
- if (actual.equals(expected))
+ if (actual.equals(expected)) {
found = true;
- break;
+ break;
+ }
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
private IResourceChangeDescriptionFactory createEmptyChangeDescription() {
return ResourceChangeValidator.getValidator().createDeltaFactory();
}
/*
* Only return the message of the status if it
* came from our test model provider
*/
private String getModelMessage(IStatus status) {
if (status instanceof ModelStatus) {
ModelStatus ms = (ModelStatus) status;
String id = ms.getModelProviderId();
if (id.equals(TestModelProvider.ID))
return status.getMessage();
}
return null;
}
protected void setUp() throws Exception {
TestModelProvider.enabled = true;
super.setUp();
project = getWorkspace().getRoot().getProject("Project");
IResource[] before = buildResources(project, new String[] {"c/", "c/b/", "c/a/", "c/x", "c/b/y", "c/b/z"});
ensureExistsInWorkspace(before, true);
assertExistsInWorkspace(before);
factory = createEmptyChangeDescription();
}
protected void tearDown() throws Exception {
TestModelProvider.enabled = false;
super.tearDown();
}
public void testCopyReplaceDeletedFolder() {
// Copy folder to replace a deleted folder
final IResource folder = project.findMember("c/b/");
IFolder destination = project.getFolder("/c/a/");
factory.delete(destination);
factory.copy(folder, destination.getFullPath());
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, folder),});
}
public void testFileChanges() {
factory.change((IFile) project.findMember("c/x"));
factory.change((IFile) project.findMember("c/b/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.CHANGED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.CHANGED, project.findMember("c/b/y"))});
}
public void testFileCopy() {
factory.copy(project.findMember("c/x"), new Path("c/x2"));
factory.copy(project.findMember("c/b/y"), new Path("c/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.COPIED, project.findMember("c/b/y"))});
}
public void testFileCreate() {
IFile file = project.getFile("file");
factory.create(file);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.ADDED, file)});
}
public void testFileInFolderCreate() {
IFolder folder = project.getFolder("folder");
IFile file = folder.getFile("file");
factory.create(folder);
factory.create(file);
IStatus status = validateChange(factory);
//this isn't very accurate, but ChangeDescription doesn't currently record recursive creates
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.ADDED, folder)});
}
public void testFileDeletion() {
factory.delete(project.findMember("c/x"));
factory.delete(project.findMember("c/b/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/b/y"))});
}
public void testFileMoves() {
factory.move(project.findMember("c/x"), new Path("c/x2"));
factory.move(project.findMember("c/b/y"), new Path("c/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.MOVED, project.findMember("c/b/y"))});
}
public void testFolderCopy() {
final IResource folder = project.findMember("c/b/");
factory.copy(folder, new Path("c/d"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, folder),});
}
public void testFolderDeletion() {
final IResource folder = project.findMember("c/b/");
factory.delete(folder);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/b")),});
}
public void testFolderMove() {
final IResource folder = project.findMember("c/b/");
factory.move(folder, new Path("c/d"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, folder),});
}
public void testMoveReplaceDeletedFolder() {
// Move to replace a deleted folder
final IResource folder = project.findMember("c/b/");
IFolder destination = project.getFolder("/c/a/");
factory.delete(destination);
factory.move(folder, destination.getFullPath());
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, folder),});
}
public void testProjectClose() {
factory.close(project);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.CLOSED, project)});
}
public void testProjectCopy() {
// A project copy
factory.copy(project, new Path("MovedProject"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, project)});
}
public void testProjectDeletion() {
// A project deletion
factory.delete(project);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project)});
}
public void testProjectMove() {
factory.move(project, new Path("MovedProject"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, project)});
}
private IStatus validateChange(IResourceChangeDescriptionFactory factory) {
return ResourceChangeValidator.getValidator().validateChange(factory.getDelta(), getMonitor());
}
}
| false | true |
private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
if (actual.equals(expected))
found = true;
break;
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
|
private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
if (actual.equals(expected)) {
found = true;
break;
}
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
|
diff --git a/src/experiments/CommonExperimentSettings.java b/src/experiments/CommonExperimentSettings.java
index aaa7c44..9d53fcc 100644
--- a/src/experiments/CommonExperimentSettings.java
+++ b/src/experiments/CommonExperimentSettings.java
@@ -1,165 +1,165 @@
/*
* Copyright 2013 Push Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package experiments;
import static util.PropertiesUtil.getProperty;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* A common set of settings for the client side of experiments. To be extended
* should further settings be required.
*
* @author nitsanw
*
*/
public class CommonExperimentSettings {
// CHECKSTYLE:OFF adding docs will add nothing...
private static final String DEFAULT_URL = "ws://localhost:8080";
private static final int DEFAULT_INBOUND_THREAD_POOL_SIZE = 1;
private static final int DEFAULT_CLIENT_INCREMENT_PAUSE_SECS = 5;
private static final double DEFAULT_CLIENT_CREATE_PAUSE_SECS = 0.001;
private static final int DEFAULT_CLIENT_INCREMENT = 50;
private static final int DEFAULT_INITIAL_CLIENTS = 50;
private static final int DEFAULT_MAX_CLIENTS = 175;
private static final int DEFAULT_MESSAGE_SIZE = 128;
private static final String DEFAULT_CONNECT_TOPIC_SELECTOR = "ROOT//";
private static final double DEFAULT_MAX_TEST_TIME_MINUTES = 5.0;
private final String[] diffusionUrls;
private final int maxClients;
private final long clientCreatePauseNanos;
private final int inboundThreadPoolSize;
private final String[] localInterfaces;
private final int initialClients;
private final int clientIncrement;
private final String connectTopicSelector;
private final int clientIncrementPauseSeconds;
private final int messageSize;
private final long maxTestTimeMillis;
private final long maxTestMessages;
private final long maxTestConnections;
private final String outputFileName;
// CHECKSTYLE:ON
/**
* Load the experiment settings from properties. Will modify the settings
* to defaults used where no value is available.
*
* @param settings ...
*/
public CommonExperimentSettings(Properties settings) {
diffusionUrls =
- getProperty(settings, "connect.string",
+ getProperty(settings, "diffusion.url",
DEFAULT_URL).split(",");
maxClients = getProperty(settings, "max.clients",
DEFAULT_MAX_CLIENTS);
initialClients = getProperty(settings, "initial.clients",
DEFAULT_INITIAL_CLIENTS);
clientIncrement = getProperty(settings, "clients.increment",
DEFAULT_CLIENT_INCREMENT);
clientCreatePauseNanos =
(long) (TimeUnit.SECONDS.toNanos(1)
* getProperty(settings,
"client.create.pause.seconds",
DEFAULT_CLIENT_CREATE_PAUSE_SECS));
clientIncrementPauseSeconds =
getProperty(settings, "client.increment.pause.seconds",
DEFAULT_CLIENT_INCREMENT_PAUSE_SECS);
inboundThreadPoolSize =
getProperty(settings, "inbound.threadpool.size",
DEFAULT_INBOUND_THREAD_POOL_SIZE);
String localsInterfaces =
getProperty(settings, "local.interfaces", "");
if (localsInterfaces == null || localsInterfaces.isEmpty()) {
localInterfaces = new String[] {};
} else {
localInterfaces = localsInterfaces.split(",");
}
connectTopicSelector =
getProperty(settings, "topic",
DEFAULT_CONNECT_TOPIC_SELECTOR);
messageSize = getProperty(settings, "message.size",
DEFAULT_MESSAGE_SIZE);
maxTestTimeMillis =
(long) (TimeUnit.MINUTES.toMillis(1)
* getProperty(settings, "max.test.time.minutes",
DEFAULT_MAX_TEST_TIME_MINUTES));
maxTestMessages = getProperty(settings, "max.test.messages", 0L);
maxTestConnections = getProperty(settings,
"max.test.connections", 0L);
outputFileName = getProperty(settings, "experiment.output", "");
}
// CHECKSTYLE:OFF adding docs will add nothing...
public String[] getDiffusionUrls() {
return diffusionUrls;
}
public int getMaxClients() {
return maxClients;
}
public long getClientCreatePauseNanos() {
return clientCreatePauseNanos;
}
public int getInboundThreadPoolSize() {
return inboundThreadPoolSize;
}
public String[] getLocalInterfaces() {
return localInterfaces;
}
public long getMaxTestTimeMillis() {
return maxTestTimeMillis;
}
public int getInitialClients() {
return initialClients;
}
public int getClientIncrement() {
return clientIncrement;
}
public String getRootTopic() {
return connectTopicSelector;
}
public int getClientIncrementPauseSeconds() {
return clientIncrementPauseSeconds;
}
public int getMessageSize() {
return messageSize;
}
public long getMaxTestMessages() {
return maxTestMessages;
}
public long getMaxTestConnections() {
return maxTestConnections;
}
public String getOutputFile() {
return outputFileName;
}
// CHECKSTYLE:ON
}
| true | true |
public CommonExperimentSettings(Properties settings) {
diffusionUrls =
getProperty(settings, "connect.string",
DEFAULT_URL).split(",");
maxClients = getProperty(settings, "max.clients",
DEFAULT_MAX_CLIENTS);
initialClients = getProperty(settings, "initial.clients",
DEFAULT_INITIAL_CLIENTS);
clientIncrement = getProperty(settings, "clients.increment",
DEFAULT_CLIENT_INCREMENT);
clientCreatePauseNanos =
(long) (TimeUnit.SECONDS.toNanos(1)
* getProperty(settings,
"client.create.pause.seconds",
DEFAULT_CLIENT_CREATE_PAUSE_SECS));
clientIncrementPauseSeconds =
getProperty(settings, "client.increment.pause.seconds",
DEFAULT_CLIENT_INCREMENT_PAUSE_SECS);
inboundThreadPoolSize =
getProperty(settings, "inbound.threadpool.size",
DEFAULT_INBOUND_THREAD_POOL_SIZE);
String localsInterfaces =
getProperty(settings, "local.interfaces", "");
if (localsInterfaces == null || localsInterfaces.isEmpty()) {
localInterfaces = new String[] {};
} else {
localInterfaces = localsInterfaces.split(",");
}
connectTopicSelector =
getProperty(settings, "topic",
DEFAULT_CONNECT_TOPIC_SELECTOR);
messageSize = getProperty(settings, "message.size",
DEFAULT_MESSAGE_SIZE);
maxTestTimeMillis =
(long) (TimeUnit.MINUTES.toMillis(1)
* getProperty(settings, "max.test.time.minutes",
DEFAULT_MAX_TEST_TIME_MINUTES));
maxTestMessages = getProperty(settings, "max.test.messages", 0L);
maxTestConnections = getProperty(settings,
"max.test.connections", 0L);
outputFileName = getProperty(settings, "experiment.output", "");
}
|
public CommonExperimentSettings(Properties settings) {
diffusionUrls =
getProperty(settings, "diffusion.url",
DEFAULT_URL).split(",");
maxClients = getProperty(settings, "max.clients",
DEFAULT_MAX_CLIENTS);
initialClients = getProperty(settings, "initial.clients",
DEFAULT_INITIAL_CLIENTS);
clientIncrement = getProperty(settings, "clients.increment",
DEFAULT_CLIENT_INCREMENT);
clientCreatePauseNanos =
(long) (TimeUnit.SECONDS.toNanos(1)
* getProperty(settings,
"client.create.pause.seconds",
DEFAULT_CLIENT_CREATE_PAUSE_SECS));
clientIncrementPauseSeconds =
getProperty(settings, "client.increment.pause.seconds",
DEFAULT_CLIENT_INCREMENT_PAUSE_SECS);
inboundThreadPoolSize =
getProperty(settings, "inbound.threadpool.size",
DEFAULT_INBOUND_THREAD_POOL_SIZE);
String localsInterfaces =
getProperty(settings, "local.interfaces", "");
if (localsInterfaces == null || localsInterfaces.isEmpty()) {
localInterfaces = new String[] {};
} else {
localInterfaces = localsInterfaces.split(",");
}
connectTopicSelector =
getProperty(settings, "topic",
DEFAULT_CONNECT_TOPIC_SELECTOR);
messageSize = getProperty(settings, "message.size",
DEFAULT_MESSAGE_SIZE);
maxTestTimeMillis =
(long) (TimeUnit.MINUTES.toMillis(1)
* getProperty(settings, "max.test.time.minutes",
DEFAULT_MAX_TEST_TIME_MINUTES));
maxTestMessages = getProperty(settings, "max.test.messages", 0L);
maxTestConnections = getProperty(settings,
"max.test.connections", 0L);
outputFileName = getProperty(settings, "experiment.output", "");
}
|
diff --git a/src/org/servalproject/rhizome/StuffDownloader.java b/src/org/servalproject/rhizome/StuffDownloader.java
index 6573e258..25d32ffb 100644
--- a/src/org/servalproject/rhizome/StuffDownloader.java
+++ b/src/org/servalproject/rhizome/StuffDownloader.java
@@ -1,353 +1,354 @@
/**
*
*/
package org.servalproject.rhizome;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.servalproject.ServalBatPhoneApplication;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* @author rbochet
*
*/
public class StuffDownloader {
/** The repository where we should get the manifest */
private String repository;
/** TAG for debugging */
public static final String TAG = "R2";
/**
* Constructor of the class.
*
* @param repository
* The root of server where the manifests are stored.
*/
public StuffDownloader(String repository) {
this.repository = repository;
Log.v(TAG, "Start downloading from " + this.repository);
List<String> manifests = fetchManifests();
List<String> dlManifests = chooseManifests(manifests);
for (String manifest : dlManifests) {
dlFile(manifest);
}
}
/**
* Download the manifest, grab the file name and download it. If the hash of
* the file downloaded is different from the hash of the manifest, discard
* both the file and the manifest.
*
* @param manifest
* The manifest address
*/
private void dlFile(String manifest) {
try {
// Download the manifest in the Rhizome directory
RhizomeRetriever.createDirectories();
Log.v(TAG, "Downloading " + manifest);
String[] tokenizedUrl = manifest.split("/");
String mfName = tokenizedUrl[tokenizedUrl.length - 1];
downloadFile(new URL(manifest), RhizomeUtils.dirRhizomeTemp + "/"
+ mfName);
// Check the key TODO
Log.v(TAG, "Loading properties from " + mfName);
Properties pManifest = new Properties();
pManifest.load(new FileInputStream(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName));
// If alright, compute the actual file URL and name
tokenizedUrl[tokenizedUrl.length - 1] = pManifest
.getProperty("name");
StringBuilder fileNameB = new StringBuilder(tokenizedUrl[0]);
for (int i = 1; i < tokenizedUrl.length; i++) {
fileNameB.append("/" + tokenizedUrl[i]);
}
String file = fileNameB.toString();
// Download it
Log.v(TAG, "Downloading " + file);
String tempFileName = RhizomeUtils.dirRhizomeTemp + "/"
+ pManifest.getProperty("name");
String downloadedFileName = RhizomeUtils.dirRhizome + "/"
+ pManifest.getProperty("name");
downloadFile(new URL(file), tempFileName);
// Check the hash
String hash = RhizomeUtils.ToHexString(RhizomeUtils
.DigestFile(new File(tempFileName)));
if (!hash.equals(pManifest.get("hash"))) {
// Hell, the hash's wrong! Delete the logical file
Log.w(TAG, "Wrong hash detected for manifest " + manifest);
} else { // If it's all right, copy it to the real repo
RhizomeUtils.CopyFileToDir(new File(tempFileName),
RhizomeUtils.dirRhizome);
RhizomeUtils.CopyFileToDir(new File(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName), RhizomeUtils.dirRhizome);
// Generate the meta file for the newly received file
String name = pManifest.getProperty("name");
String version = pManifest.getProperty("version");
try {
RhizomeFile.GenerateMetaForFilename(name, Float
.parseFloat(version));
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
// Notify the main view that a file has been updated
Handler handler = RhizomeRetriever.getHandlerInstance();
if (handler != null) {
Message updateMessage = handler.obtainMessage(
RhizomeRetriever.MSG_UPD, name + " (v. " + version
+ ")");
handler.sendMessage(updateMessage);
}
if (downloadedFileName.toLowerCase().endsWith(".rpml"))
{
// File is a public message log - so we should tell batphone to
// look for messages in the file.
MessageLogExaminer.examineLog(downloadedFileName);
}
if (downloadedFileName.toLowerCase().endsWith(".map")) {
// File is a map.
// copy into place and notify user to restart mapping
RhizomeUtils.CopyFileToDir(new File(downloadedFileName),
new File(
"/sdcard/serval/mapping-services/mapsforge/"));
// TODO: Create a notification or otherwise tell the mapping
// application that the
// map is available.
}
if (downloadedFileName.toLowerCase().endsWith(".apk")) {
PackageManager pm = ServalBatPhoneApplication.context
.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(
downloadedFileName, 0);
if (info.packageName.equals("org.servalproject")) {
int downloadedVersion = info.versionCode;
try {
int installedVersion = ServalBatPhoneApplication.context
.getPackageManager().getPackageInfo(
ServalBatPhoneApplication.context
.getPackageName(), 0).versionCode;
if (downloadedVersion > installedVersion) {
// We have a newer version of Serval BatPhone,
// open it to try to install it. This will only
// work if the signing keys match, so we don't
// need to do any further authenticity check
// here.
Intent i = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(downloadedFileName))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.setType(
"application/android.com.app");
ServalBatPhoneApplication.context
.startActivity(i);
}
} catch (NameNotFoundException e) {
Log.e("BatPhone", e.toString(), e);
}
}
}
}
// Delete the files in the temp dir
new RhizomeFile(RhizomeUtils.dirRhizomeTemp,
pManifest.getProperty("name")).delete();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
private void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Choose the interesting manifests among a list of the manifest that can be
* downloaded from an host. If we dont have Manifest nor Meta for this file,
* we'll download it. If we have just the meta, it means the user delete the
* file ; so we download it just if it is a new version.
*
* @param manifests
* The list of all the manifests URL
* @return A list of the selected manifests
*/
private List<String> chooseManifests(List<String> manifests) {
List<String> ret = new ArrayList<String>();
// Iterate
for (String manifest : manifests) {
// "Unwrapp" the names
String mfName = manifest.split("/")[manifest.split("/").length - 1];
String metaName = mfName.replace("manifest", "meta");
// Check if it exists on the local repo
if (!(new File(RhizomeUtils.dirRhizome, metaName).exists())) {
// We add it to the DL list
ret.add(manifest);
} else { // The manifest already exists ; but is it a new version ?
try {
// DL the new manifest in a temp directory
Log.v(TAG, "Downloading " + manifest);
downloadFile(new URL(manifest), RhizomeUtils.dirRhizomeTemp
+ "/" + mfName);
// Compare the new manifest to the old meta ; if new.version
// > old.version,
// DL
Properties newManifest = new Properties();
newManifest.load(new FileInputStream(
RhizomeUtils.dirRhizomeTemp + "/" + mfName));
float nmversion = Float.parseFloat((String) newManifest
.get("version"));
Properties oldMeta = new Properties();
oldMeta.load(new FileInputStream(RhizomeUtils.dirRhizome
+ "/" + metaName));
float omversion = Float.parseFloat((String) oldMeta
.get("version"));
Log.e(TAG, "comparing manifest versions: " + nmversion
+ " vs " + omversion);
Log.e(TAG, "comparing manifest versions: L>R = "
+ (nmversion > omversion));
if (nmversion > omversion) {
ret.add(manifest);
}
} catch (IOException e) {
Log.e(TAG, "Error evaluating if the manifest " + manifest
+ " version.");
e.printStackTrace();
}
}
}
return ret;
}
/**
* Fetch the list of the manifests on the server.
*
* @return The list of manifests.
*/
static final Pattern pattern = Pattern.compile("<a href=\"(.+?)\"");
private List<String> fetchManifests() {
List<String> manifests = new ArrayList<String>();
try {
URL repoURL = new URL(repository);
BufferedReader in = new BufferedReader(new InputStreamReader(
repoURL.openStream()), 8192);
StringBuilder sb = new StringBuilder();
// Read each line
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
Matcher matcher = pattern.matcher(sb.toString());
while (matcher.find()) {
String url = matcher.group(1);
manifests.add(repository + url);
}
// Close stream
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return manifests;
}
/**
* Download a file using HTTP.
*
* @param file
* The URL of the file
* @param path
* The path were the file will be saved on the local FS.
* @throws IOException
* If something goes wrong
*/
private void downloadFile(URL url, String path) throws IOException {
URLConnection uc = url.openConnection();
int contentLength = uc.getContentLength();
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw, 8192);
if (contentLength < 0)
return;
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected "
+ contentLength + " bytes");
}
// Save it !
Log.e(TAG, "PATH :: " + path);
FileOutputStream out = new FileOutputStream(path);
out.write(data);
out.flush();
out.close();
}
}
| true | true |
private void dlFile(String manifest) {
try {
// Download the manifest in the Rhizome directory
RhizomeRetriever.createDirectories();
Log.v(TAG, "Downloading " + manifest);
String[] tokenizedUrl = manifest.split("/");
String mfName = tokenizedUrl[tokenizedUrl.length - 1];
downloadFile(new URL(manifest), RhizomeUtils.dirRhizomeTemp + "/"
+ mfName);
// Check the key TODO
Log.v(TAG, "Loading properties from " + mfName);
Properties pManifest = new Properties();
pManifest.load(new FileInputStream(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName));
// If alright, compute the actual file URL and name
tokenizedUrl[tokenizedUrl.length - 1] = pManifest
.getProperty("name");
StringBuilder fileNameB = new StringBuilder(tokenizedUrl[0]);
for (int i = 1; i < tokenizedUrl.length; i++) {
fileNameB.append("/" + tokenizedUrl[i]);
}
String file = fileNameB.toString();
// Download it
Log.v(TAG, "Downloading " + file);
String tempFileName = RhizomeUtils.dirRhizomeTemp + "/"
+ pManifest.getProperty("name");
String downloadedFileName = RhizomeUtils.dirRhizome + "/"
+ pManifest.getProperty("name");
downloadFile(new URL(file), tempFileName);
// Check the hash
String hash = RhizomeUtils.ToHexString(RhizomeUtils
.DigestFile(new File(tempFileName)));
if (!hash.equals(pManifest.get("hash"))) {
// Hell, the hash's wrong! Delete the logical file
Log.w(TAG, "Wrong hash detected for manifest " + manifest);
} else { // If it's all right, copy it to the real repo
RhizomeUtils.CopyFileToDir(new File(tempFileName),
RhizomeUtils.dirRhizome);
RhizomeUtils.CopyFileToDir(new File(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName), RhizomeUtils.dirRhizome);
// Generate the meta file for the newly received file
String name = pManifest.getProperty("name");
String version = pManifest.getProperty("version");
try {
RhizomeFile.GenerateMetaForFilename(name, Float
.parseFloat(version));
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
// Notify the main view that a file has been updated
Handler handler = RhizomeRetriever.getHandlerInstance();
if (handler != null) {
Message updateMessage = handler.obtainMessage(
RhizomeRetriever.MSG_UPD, name + " (v. " + version
+ ")");
handler.sendMessage(updateMessage);
}
if (downloadedFileName.toLowerCase().endsWith(".rpml"))
{
// File is a public message log - so we should tell batphone to
// look for messages in the file.
MessageLogExaminer.examineLog(downloadedFileName);
}
if (downloadedFileName.toLowerCase().endsWith(".map")) {
// File is a map.
// copy into place and notify user to restart mapping
RhizomeUtils.CopyFileToDir(new File(downloadedFileName),
new File(
"/sdcard/serval/mapping-services/mapsforge/"));
// TODO: Create a notification or otherwise tell the mapping
// application that the
// map is available.
}
if (downloadedFileName.toLowerCase().endsWith(".apk")) {
PackageManager pm = ServalBatPhoneApplication.context
.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(
downloadedFileName, 0);
if (info.packageName.equals("org.servalproject")) {
int downloadedVersion = info.versionCode;
try {
int installedVersion = ServalBatPhoneApplication.context
.getPackageManager().getPackageInfo(
ServalBatPhoneApplication.context
.getPackageName(), 0).versionCode;
if (downloadedVersion > installedVersion) {
// We have a newer version of Serval BatPhone,
// open it to try to install it. This will only
// work if the signing keys match, so we don't
// need to do any further authenticity check
// here.
Intent i = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(downloadedFileName))
.setType(
"application/android.com.app");
ServalBatPhoneApplication.context
.startActivity(i);
}
} catch (NameNotFoundException e) {
Log.e("BatPhone", e.toString(), e);
}
}
}
}
// Delete the files in the temp dir
new RhizomeFile(RhizomeUtils.dirRhizomeTemp,
pManifest.getProperty("name")).delete();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
|
private void dlFile(String manifest) {
try {
// Download the manifest in the Rhizome directory
RhizomeRetriever.createDirectories();
Log.v(TAG, "Downloading " + manifest);
String[] tokenizedUrl = manifest.split("/");
String mfName = tokenizedUrl[tokenizedUrl.length - 1];
downloadFile(new URL(manifest), RhizomeUtils.dirRhizomeTemp + "/"
+ mfName);
// Check the key TODO
Log.v(TAG, "Loading properties from " + mfName);
Properties pManifest = new Properties();
pManifest.load(new FileInputStream(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName));
// If alright, compute the actual file URL and name
tokenizedUrl[tokenizedUrl.length - 1] = pManifest
.getProperty("name");
StringBuilder fileNameB = new StringBuilder(tokenizedUrl[0]);
for (int i = 1; i < tokenizedUrl.length; i++) {
fileNameB.append("/" + tokenizedUrl[i]);
}
String file = fileNameB.toString();
// Download it
Log.v(TAG, "Downloading " + file);
String tempFileName = RhizomeUtils.dirRhizomeTemp + "/"
+ pManifest.getProperty("name");
String downloadedFileName = RhizomeUtils.dirRhizome + "/"
+ pManifest.getProperty("name");
downloadFile(new URL(file), tempFileName);
// Check the hash
String hash = RhizomeUtils.ToHexString(RhizomeUtils
.DigestFile(new File(tempFileName)));
if (!hash.equals(pManifest.get("hash"))) {
// Hell, the hash's wrong! Delete the logical file
Log.w(TAG, "Wrong hash detected for manifest " + manifest);
} else { // If it's all right, copy it to the real repo
RhizomeUtils.CopyFileToDir(new File(tempFileName),
RhizomeUtils.dirRhizome);
RhizomeUtils.CopyFileToDir(new File(RhizomeUtils.dirRhizomeTemp
+ "/" + mfName), RhizomeUtils.dirRhizome);
// Generate the meta file for the newly received file
String name = pManifest.getProperty("name");
String version = pManifest.getProperty("version");
try {
RhizomeFile.GenerateMetaForFilename(name, Float
.parseFloat(version));
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
// Notify the main view that a file has been updated
Handler handler = RhizomeRetriever.getHandlerInstance();
if (handler != null) {
Message updateMessage = handler.obtainMessage(
RhizomeRetriever.MSG_UPD, name + " (v. " + version
+ ")");
handler.sendMessage(updateMessage);
}
if (downloadedFileName.toLowerCase().endsWith(".rpml"))
{
// File is a public message log - so we should tell batphone to
// look for messages in the file.
MessageLogExaminer.examineLog(downloadedFileName);
}
if (downloadedFileName.toLowerCase().endsWith(".map")) {
// File is a map.
// copy into place and notify user to restart mapping
RhizomeUtils.CopyFileToDir(new File(downloadedFileName),
new File(
"/sdcard/serval/mapping-services/mapsforge/"));
// TODO: Create a notification or otherwise tell the mapping
// application that the
// map is available.
}
if (downloadedFileName.toLowerCase().endsWith(".apk")) {
PackageManager pm = ServalBatPhoneApplication.context
.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(
downloadedFileName, 0);
if (info.packageName.equals("org.servalproject")) {
int downloadedVersion = info.versionCode;
try {
int installedVersion = ServalBatPhoneApplication.context
.getPackageManager().getPackageInfo(
ServalBatPhoneApplication.context
.getPackageName(), 0).versionCode;
if (downloadedVersion > installedVersion) {
// We have a newer version of Serval BatPhone,
// open it to try to install it. This will only
// work if the signing keys match, so we don't
// need to do any further authenticity check
// here.
Intent i = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(downloadedFileName))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.setType(
"application/android.com.app");
ServalBatPhoneApplication.context
.startActivity(i);
}
} catch (NameNotFoundException e) {
Log.e("BatPhone", e.toString(), e);
}
}
}
}
// Delete the files in the temp dir
new RhizomeFile(RhizomeUtils.dirRhizomeTemp,
pManifest.getProperty("name")).delete();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/cadpage/src/net/anei/cadpage/parsers/MD/MDKentCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/MD/MDKentCountyParser.java
index 1d606f96e..d904c37e1 100644
--- a/cadpage/src/net/anei/cadpage/parsers/MD/MDKentCountyParser.java
+++ b/cadpage/src/net/anei/cadpage/parsers/MD/MDKentCountyParser.java
@@ -1,37 +1,37 @@
package net.anei.cadpage.parsers.MD;
import net.anei.cadpage.parsers.FieldProgramParser;
/*
Kent County, MD
Contact: Travis Nelson <[email protected]>
Sender: [email protected]
System: PSSI
CT:ASSAULT 835 HIGH ST BOX:6001 DUE:A8 PM1-1
CT:MVC/PT NOT ALERT W CAMPUS AVE / WASHINGTON AVE BOX:6001 DUE:E6 R6 A8 PM1-1
CT:CARDIAC ARREST 25129 WYMONT PARK RD BOX:5005 DUE:A8
CT:ASSAULT 835 HIGH ST BOX:6001 DUE:A8 PM1-1
CT:UNCON/SYNCOPAL 818 HIGH ST BOX:6001 DUE:A8 PM1-1
CT:EMOTIONAL DISORDER 104 VICKERS DR @KENT CO DETENTION CE BOX:6001 DUE:A81
CT:ALLERGIC REACTION TACO BELL/KFC @709 WASHINGTON AVE BOX:6001 DUE:A8 PM1-1
CT:MVC RT 213 / RT 291 BOX:6001 DUE:RA8E
CT:MVC MORGNEC RD / TALBOT BLVD BOX:6001 DUE:E6 A8 PM1-1
CT:STRUCTURE FIRE 408 MORGNEC RD APT 103 BOX:6001 DUE:E6 E4 QAE71 QAE52 TWR6 QATWL5 R6 RP4 A8 A81 PM1-1
CT:CHEST PAIN 11673 KENNEDYVILLE RD BOX:4002 DUE:E4 A8 PM1-1
*/
public class MDKentCountyParser extends FieldProgramParser {
public MDKentCountyParser() {
- super("WILLIAMSON COUNTY", "TX",
+ super("KENT COUNTY", "MD",
"CT:ADDR! BOX:BOX! DUE:UNIT!");
}
@Override
public String getFilter() {
return "[email protected]";
}
}
| true | true |
public MDKentCountyParser() {
super("WILLIAMSON COUNTY", "TX",
"CT:ADDR! BOX:BOX! DUE:UNIT!");
}
|
public MDKentCountyParser() {
super("KENT COUNTY", "MD",
"CT:ADDR! BOX:BOX! DUE:UNIT!");
}
|
diff --git a/src/org/rsbot/security/RestrictedSecurityManager.java b/src/org/rsbot/security/RestrictedSecurityManager.java
index 2389ce32..88c2b8ab 100644
--- a/src/org/rsbot/security/RestrictedSecurityManager.java
+++ b/src/org/rsbot/security/RestrictedSecurityManager.java
@@ -1,233 +1,233 @@
package org.rsbot.security;
import org.rsbot.Application;
import org.rsbot.gui.BotGUI;
import org.rsbot.script.Script;
import org.rsbot.service.ScriptDeliveryNetwork;
import java.io.FileDescriptor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Permission;
import java.util.ArrayList;
/**
* @author Paris
*/
public class RestrictedSecurityManager extends SecurityManager {
private String getCallingClass() {
final String prefix = Application.class.getPackage().getName() + ".";
for (StackTraceElement s : Thread.currentThread().getStackTrace()) {
final String name = s.getClassName();
if (name.startsWith(prefix) && !name.equals(RestrictedSecurityManager.class.getName())) {
return name;
}
}
return "";
}
private boolean isCallerScript() {
final String name = getCallingClass();
if (name.isEmpty()) {
return false;
}
return name.startsWith(Script.class.getName());
}
public void checkAccept(String host, int port) {
throw new SecurityException();
}
public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
- // NOTE: prefix with '.' boundary because .example.com won't match on hacked-example.com
+ // NOTE: give an exact host name!
whitelist.add("imageshack.us");
whitelist.add("tinypic.com");
whitelist.add("imgur.com");
whitelist.add("powerbot.org");
whitelist.add("runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
if (host.equalsIgnoreCase(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
private boolean isIpAddress(String check) {
final int l = check.length();
if (l < 7 || l > 15) {
return false;
}
String[] parts = check.split("\\.", 4);
if (parts.length != 4) {
return false;
}
for (int i = 0; i < 4; i++) {
int n = Integer.parseInt(parts[i]);
if (n < 0 || n > 255) {
return false;
}
}
return true;
}
public void checkConnect(String host, int port, Object context) {
checkConnect(host, port);
}
public void checkCreateClassLoader() {
super.checkCreateClassLoader();
}
public void checkDelete(String file) {
if (isCallerScript()) {
throw new SecurityException();
} else {
super.checkDelete(file);
}
}
public void checkExec(String cmd) {
final String calling = getCallingClass();
if (calling.equals(ScriptDeliveryNetwork.class.getName()) || calling.equals(BotGUI.class.getName())) {
super.checkExec(cmd);
} else {
throw new SecurityException();
}
}
public void checkExit(int status) {
final String calling = getCallingClass();
if (calling.equals(BotGUI.class.getName())) {
super.checkExit(status);
} else {
throw new SecurityException();
}
}
public void checkLink(String lib) {
super.checkLink(lib);
}
public void checkListen(int port) {
throw new SecurityException();
}
public void checkMemberAccess(Class<?> clazz, int which) {
super.checkMemberAccess(clazz, which);
}
public void checkMulticast(InetAddress maddr) {
throw new SecurityException();
}
public void checkMulticast(InetAddress maddr, byte ttl) {
throw new SecurityException();
}
public void checkPackageAccess(String pkg) {
super.checkPackageAccess(pkg);
}
public void checkPackageDefinition(String pkg) {
super.checkPackageDefinition(pkg);
}
public void checkPermission(Permission perm) {
//super.checkPermission(perm);
}
public void checkPermission(Permission perm, Object context) {
//super.checkPermission(perm, context);
}
public void checkPrintJobAccess() {
throw new SecurityException();
}
public void checkPropertiesAccess() {
super.checkPropertiesAccess();
}
public void checkPropertyAccess(String key) {
super.checkPropertyAccess(key);
}
public void checkRead(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkRead(fd);
}
public void checkRead(String file) {
super.checkRead(file);
}
public void checkRead(String file, Object context) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkRead(file, context);
}
public void checkSecurityAccess(String target) {
super.checkSecurityAccess(target);
}
public void checkSetFactory() {
super.checkSetFactory();
}
public void checkSystemClipboardAccess() {
throw new SecurityException();
}
public boolean checkTopLevelWindow(Object window) {
return super.checkTopLevelWindow(window);
}
public void checkWrite(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkWrite(fd);
}
public void checkWrite(String file) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkWrite(file);
}
}
| true | true |
public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: prefix with '.' boundary because .example.com won't match on hacked-example.com
whitelist.add("imageshack.us");
whitelist.add("tinypic.com");
whitelist.add("imgur.com");
whitelist.add("powerbot.org");
whitelist.add("runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
if (host.equalsIgnoreCase(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
|
public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: give an exact host name!
whitelist.add("imageshack.us");
whitelist.add("tinypic.com");
whitelist.add("imgur.com");
whitelist.add("powerbot.org");
whitelist.add("runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
if (host.equalsIgnoreCase(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
|
diff --git a/codemonkey-core/src/main/java/com/codemonkey/domain/AbsEntity.java b/codemonkey-core/src/main/java/com/codemonkey/domain/AbsEntity.java
index 158c612..1e8abb8 100644
--- a/codemonkey-core/src/main/java/com/codemonkey/domain/AbsEntity.java
+++ b/codemonkey-core/src/main/java/com/codemonkey/domain/AbsEntity.java
@@ -1,167 +1,168 @@
package com.codemonkey.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
import org.json.JSONObject;
import com.codemonkey.annotation.Label;
import com.codemonkey.utils.OgnlUtils;
@MappedSuperclass
public class AbsEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator="pkgenerator")
@GenericGenerator(name="pkgenerator", strategy = "increment")
@Label("自动编号")
private Long id;
@Label("编码")
@Index(name = "code_index")
private String code;
@Label("名称")
@Index(name = "name_index")
private String name;
@Label("描述")
private String description;
@Version
private Integer version;
@Transient
private Integer originVersion;
@Label("创建时间")
private Date creationDate;
@Label("创建人")
private String createdBy;
@Label("修改时间")
private Date modificationDate;
@Label("修改人")
private String modifiedBy;
JSONObject json() {
JSONObject jo = new JSONObject();
jo.put("id", OgnlUtils.stringValue("id", this));
jo.put("originVersion", OgnlUtils.stringValue("originVersion", this));
+ jo.put("code", OgnlUtils.stringValue("code", this));
jo.put("name", OgnlUtils.stringValue("name", this));
jo.put("description", OgnlUtils.stringValue("description", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("createdBy", OgnlUtils.stringValue("createdBy", this));
jo.put("modifiedBy", OgnlUtils.stringValue("modifiedBy", this));
return jo;
}
public boolean isOptimisticLockingFailure() {
if (getOriginVersion() == null){
return false;
}
return !getOriginVersion().equals(this.version);
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getOriginVersion() {
if (originVersion == null) {
this.originVersion = this.version;
}
return originVersion;
}
public void setOriginVersion(Integer originVersion) {
this.originVersion = originVersion;
}
}
| true | true |
JSONObject json() {
JSONObject jo = new JSONObject();
jo.put("id", OgnlUtils.stringValue("id", this));
jo.put("originVersion", OgnlUtils.stringValue("originVersion", this));
jo.put("name", OgnlUtils.stringValue("name", this));
jo.put("description", OgnlUtils.stringValue("description", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("createdBy", OgnlUtils.stringValue("createdBy", this));
jo.put("modifiedBy", OgnlUtils.stringValue("modifiedBy", this));
return jo;
}
|
JSONObject json() {
JSONObject jo = new JSONObject();
jo.put("id", OgnlUtils.stringValue("id", this));
jo.put("originVersion", OgnlUtils.stringValue("originVersion", this));
jo.put("code", OgnlUtils.stringValue("code", this));
jo.put("name", OgnlUtils.stringValue("name", this));
jo.put("description", OgnlUtils.stringValue("description", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("creationDate", OgnlUtils.stringValue("creationDate", this));
jo.put("createdBy", OgnlUtils.stringValue("createdBy", this));
jo.put("modifiedBy", OgnlUtils.stringValue("modifiedBy", this));
return jo;
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/ResetCommand.java b/src/com/wolvencraft/prison/mines/cmd/ResetCommand.java
index 06b5b94..42f928a 100644
--- a/src/com/wolvencraft/prison/mines/cmd/ResetCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/ResetCommand.java
@@ -1,128 +1,128 @@
package com.wolvencraft.prison.mines.cmd;
import com.wolvencraft.prison.mines.CommandManager;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.util.ExtensionLoader;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
public class ResetCommand implements BaseCommand {
public boolean run(String[] args) {
Mine curMine = null;
String generator = "";
if(args.length == 1) {
getHelp();
return true;
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("all")) {
boolean success = true;
for(Mine mine : PrisonMine.getLocalMines()) {
if(!CommandManager.RESET.run(mine.getId())) success = false;
}
return success;
} else curMine = Mine.get(args[1]);
} else if(args.length == 3) {
curMine = Mine.get(args[1]);
generator = args[2];
} else {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
if(curMine == null) {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
boolean automatic;
if(CommandManager.getSender() == null) {
automatic = true;
} else {
automatic = false;
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + curMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: MANUAL (command/sign)");
}
- String broadcastMessage;
+ String broadcastMessage = "";
if(automatic) {
for(Mine childMine : curMine.getChildren()) {
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + childMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: parent mine is resetting (" + curMine.getId() + ")");
CommandManager.RESET.run(childMine.getId());
Message.debug("| Reached the end of the report for " + childMine.getId());
Message.debug("+---------------------------------------------");
}
if(curMine.getAutomaticReset() && curMine.getResetsIn() <= 0)
broadcastMessage = PrisonMine.getLanguage().RESET_TIMED;
else if(curMine.getCompositionReset() && curMine.getCurrentPercent() <= curMine.getRequiredPercent())
broadcastMessage = PrisonMine.getLanguage().RESET_COMPOSITION;
else
broadcastMessage = PrisonMine.getLanguage().RESET_AUTOMATIC;
curMine.resetTimer();
} else {
if(!Util.hasPermission("prison.mine.reset.manual." + curMine.getId()) && !Util.hasPermission("prison.mine.reset.manual")) {
Message.sendError(PrisonMine.getLanguage().ERROR_ACCESS);
Message.debug("| Insufficient permissions. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !Util.hasPermission("prison.mine.bypass.cooldown")) {
Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
Message.debug("| Cooldown is in effect. Checking for bypass...");
Message.debug("| Failed. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getAutomaticReset() && PrisonMine.getSettings().MANUALTIMERRESET) {
Message.debug("| Resetting the timer (config)");
curMine.resetTimer();
}
broadcastMessage = PrisonMine.getLanguage().RESET_MANUAL;
}
if(generator.equals("")) generator = curMine.getGenerator();
if(curMine.getCooldown()) curMine.resetCooldown();
if(!(curMine.reset(generator))) return false;
if(!automatic || curMine.getParent() == null) {
broadcastMessage = Util.parseVars(broadcastMessage, curMine);
if(!curMine.getSilent()) Message.broadcast(broadcastMessage);
else if(!automatic) Message.sendSuccess(broadcastMessage);
}
if(!automatic) {
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
}
return true;
}
public void getHelp() {
Message.formatHeader(20, "Reset");
Message.formatHelp("reset", "<name> [generator]", "Resets the mine manually");
Message.formatMessage("Resets the mine according to the generation rules");
Message.formatMessage("The following generators are supported: ");
Message.formatMessage(ExtensionLoader.list());
return;
}
public void getHelpLine() { Message.formatHelp("reset", "<name> [generator]", "Resets the mine manually", "prison.mine.reset.manual"); }
}
| true | true |
public boolean run(String[] args) {
Mine curMine = null;
String generator = "";
if(args.length == 1) {
getHelp();
return true;
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("all")) {
boolean success = true;
for(Mine mine : PrisonMine.getLocalMines()) {
if(!CommandManager.RESET.run(mine.getId())) success = false;
}
return success;
} else curMine = Mine.get(args[1]);
} else if(args.length == 3) {
curMine = Mine.get(args[1]);
generator = args[2];
} else {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
if(curMine == null) {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
boolean automatic;
if(CommandManager.getSender() == null) {
automatic = true;
} else {
automatic = false;
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + curMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: MANUAL (command/sign)");
}
String broadcastMessage;
if(automatic) {
for(Mine childMine : curMine.getChildren()) {
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + childMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: parent mine is resetting (" + curMine.getId() + ")");
CommandManager.RESET.run(childMine.getId());
Message.debug("| Reached the end of the report for " + childMine.getId());
Message.debug("+---------------------------------------------");
}
if(curMine.getAutomaticReset() && curMine.getResetsIn() <= 0)
broadcastMessage = PrisonMine.getLanguage().RESET_TIMED;
else if(curMine.getCompositionReset() && curMine.getCurrentPercent() <= curMine.getRequiredPercent())
broadcastMessage = PrisonMine.getLanguage().RESET_COMPOSITION;
else
broadcastMessage = PrisonMine.getLanguage().RESET_AUTOMATIC;
curMine.resetTimer();
} else {
if(!Util.hasPermission("prison.mine.reset.manual." + curMine.getId()) && !Util.hasPermission("prison.mine.reset.manual")) {
Message.sendError(PrisonMine.getLanguage().ERROR_ACCESS);
Message.debug("| Insufficient permissions. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !Util.hasPermission("prison.mine.bypass.cooldown")) {
Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
Message.debug("| Cooldown is in effect. Checking for bypass...");
Message.debug("| Failed. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getAutomaticReset() && PrisonMine.getSettings().MANUALTIMERRESET) {
Message.debug("| Resetting the timer (config)");
curMine.resetTimer();
}
broadcastMessage = PrisonMine.getLanguage().RESET_MANUAL;
}
if(generator.equals("")) generator = curMine.getGenerator();
if(curMine.getCooldown()) curMine.resetCooldown();
if(!(curMine.reset(generator))) return false;
if(!automatic || curMine.getParent() == null) {
broadcastMessage = Util.parseVars(broadcastMessage, curMine);
if(!curMine.getSilent()) Message.broadcast(broadcastMessage);
else if(!automatic) Message.sendSuccess(broadcastMessage);
}
if(!automatic) {
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
}
return true;
}
|
public boolean run(String[] args) {
Mine curMine = null;
String generator = "";
if(args.length == 1) {
getHelp();
return true;
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("all")) {
boolean success = true;
for(Mine mine : PrisonMine.getLocalMines()) {
if(!CommandManager.RESET.run(mine.getId())) success = false;
}
return success;
} else curMine = Mine.get(args[1]);
} else if(args.length == 3) {
curMine = Mine.get(args[1]);
generator = args[2];
} else {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
if(curMine == null) {
Message.sendError(PrisonMine.getLanguage().ERROR_ARGUMENTS);
return false;
}
boolean automatic;
if(CommandManager.getSender() == null) {
automatic = true;
} else {
automatic = false;
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + curMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: MANUAL (command/sign)");
}
String broadcastMessage = "";
if(automatic) {
for(Mine childMine : curMine.getChildren()) {
Message.debug("+---------------------------------------------");
Message.debug("| Mine " + childMine.getId() + " is resetting. Reset report:");
Message.debug("| Reset cause: parent mine is resetting (" + curMine.getId() + ")");
CommandManager.RESET.run(childMine.getId());
Message.debug("| Reached the end of the report for " + childMine.getId());
Message.debug("+---------------------------------------------");
}
if(curMine.getAutomaticReset() && curMine.getResetsIn() <= 0)
broadcastMessage = PrisonMine.getLanguage().RESET_TIMED;
else if(curMine.getCompositionReset() && curMine.getCurrentPercent() <= curMine.getRequiredPercent())
broadcastMessage = PrisonMine.getLanguage().RESET_COMPOSITION;
else
broadcastMessage = PrisonMine.getLanguage().RESET_AUTOMATIC;
curMine.resetTimer();
} else {
if(!Util.hasPermission("prison.mine.reset.manual." + curMine.getId()) && !Util.hasPermission("prison.mine.reset.manual")) {
Message.sendError(PrisonMine.getLanguage().ERROR_ACCESS);
Message.debug("| Insufficient permissions. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !Util.hasPermission("prison.mine.bypass.cooldown")) {
Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
Message.debug("| Cooldown is in effect. Checking for bypass...");
Message.debug("| Failed. Cancelling...");
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
return false;
}
if(curMine.getAutomaticReset() && PrisonMine.getSettings().MANUALTIMERRESET) {
Message.debug("| Resetting the timer (config)");
curMine.resetTimer();
}
broadcastMessage = PrisonMine.getLanguage().RESET_MANUAL;
}
if(generator.equals("")) generator = curMine.getGenerator();
if(curMine.getCooldown()) curMine.resetCooldown();
if(!(curMine.reset(generator))) return false;
if(!automatic || curMine.getParent() == null) {
broadcastMessage = Util.parseVars(broadcastMessage, curMine);
if(!curMine.getSilent()) Message.broadcast(broadcastMessage);
else if(!automatic) Message.sendSuccess(broadcastMessage);
}
if(!automatic) {
Message.debug("| Reached the end of the report for " + curMine.getId());
Message.debug("+---------------------------------------------");
}
return true;
}
|
diff --git a/src/joshua/decoder/ff/PhraseModelFF.java b/src/joshua/decoder/ff/PhraseModelFF.java
index f79a2c96..1f1506cb 100644
--- a/src/joshua/decoder/ff/PhraseModelFF.java
+++ b/src/joshua/decoder/ff/PhraseModelFF.java
@@ -1,90 +1,90 @@
package joshua.decoder.ff;
import java.util.logging.Level;
import java.util.logging.Logger;
import joshua.decoder.ff.tm.Rule;
import joshua.decoder.ff.tm.GrammarFactory;
import joshua.decoder.chart_parser.SourcePath;
import joshua.corpus.Vocabulary;
/**
* This feature handles the list of dense features that may be associated with the rules in a
* grammar file. The feature names of these dense rules are a function of the phrase model owner.
* When the feature is loaded, it queries the weights for the set of features that are active for
* this grammar, storing them in an array.
*
* @author Matt Post <[email protected]>
* @author Zhifei Li <[email protected]>
*/
public class PhraseModelFF extends PrecomputableFF {
private static final Logger logger = Logger.getLogger(PhraseModelFF.class.getName());
/* An array for storing the dense set of features */
private float[] featureWeights;
/* The owner of the grammar. */
private String owner;
private int ownerID;
public PhraseModelFF(FeatureVector weights, GrammarFactory grammar, String owner) {
super(weights, "PhraseModel_" + owner, "");
// Store the owner.
this.owner = owner;
this.ownerID = Vocabulary.id(owner);
/* Now query the weights to see how many features there are active for this template. We go
* through, finding all weights of the form "PhraseModel_OWNER_NUMBER". The highest NUMBER is
* the length of the dense array. We record the weights for quick and easy application when we
* are later asked to score a rule.
*/
String prefix = name + "_";
int maxIndex = 0;
for (String key: weights.keySet()) {
if (key.startsWith(prefix)) {
- int index = Integer.parseInt(key.substring(key.lastIndexOf("_")));
+ int index = Integer.parseInt(key.substring(key.lastIndexOf("_") + 1));
if (index > maxIndex)
maxIndex = index;
}
}
featureWeights = new float[maxIndex+1];
for (int i = 0; i <= maxIndex; i++) {
String key = String.format("%s_%d", name, i);
featureWeights[i] = (weights.containsKey(key))
? weights.get(key)
: 0.0f;
}
}
/**
* Compute the features triggered by the supplied rule.
*/
public FeatureVector computeFeatures(final Rule rule) {
FeatureVector featureDelta = new FeatureVector();
float[] featureScores = rule.getDenseFeatures();
for (int i = 0; i < featureScores.length; i++)
featureDelta.put(String.format("PhraseModel_%s_%d", owner, i), featureScores[i]);
return featureDelta;
}
public float computeCost(final Rule rule) {
float cost = 0.0f;
if (this.ownerID == rule.getOwner()) {
float[] featureScores = rule.getDenseFeatures();
for (int i = 0; i < featureWeights.length; i++)
cost += featureWeights[i] + featureScores[i];
}
return cost;
}
}
| true | true |
public PhraseModelFF(FeatureVector weights, GrammarFactory grammar, String owner) {
super(weights, "PhraseModel_" + owner, "");
// Store the owner.
this.owner = owner;
this.ownerID = Vocabulary.id(owner);
/* Now query the weights to see how many features there are active for this template. We go
* through, finding all weights of the form "PhraseModel_OWNER_NUMBER". The highest NUMBER is
* the length of the dense array. We record the weights for quick and easy application when we
* are later asked to score a rule.
*/
String prefix = name + "_";
int maxIndex = 0;
for (String key: weights.keySet()) {
if (key.startsWith(prefix)) {
int index = Integer.parseInt(key.substring(key.lastIndexOf("_")));
if (index > maxIndex)
maxIndex = index;
}
}
featureWeights = new float[maxIndex+1];
for (int i = 0; i <= maxIndex; i++) {
String key = String.format("%s_%d", name, i);
featureWeights[i] = (weights.containsKey(key))
? weights.get(key)
: 0.0f;
}
}
|
public PhraseModelFF(FeatureVector weights, GrammarFactory grammar, String owner) {
super(weights, "PhraseModel_" + owner, "");
// Store the owner.
this.owner = owner;
this.ownerID = Vocabulary.id(owner);
/* Now query the weights to see how many features there are active for this template. We go
* through, finding all weights of the form "PhraseModel_OWNER_NUMBER". The highest NUMBER is
* the length of the dense array. We record the weights for quick and easy application when we
* are later asked to score a rule.
*/
String prefix = name + "_";
int maxIndex = 0;
for (String key: weights.keySet()) {
if (key.startsWith(prefix)) {
int index = Integer.parseInt(key.substring(key.lastIndexOf("_") + 1));
if (index > maxIndex)
maxIndex = index;
}
}
featureWeights = new float[maxIndex+1];
for (int i = 0; i <= maxIndex; i++) {
String key = String.format("%s_%d", name, i);
featureWeights[i] = (weights.containsKey(key))
? weights.get(key)
: 0.0f;
}
}
|
diff --git a/EnchantMore.java b/EnchantMore.java
index 6487f4d..61a7a67 100644
--- a/EnchantMore.java
+++ b/EnchantMore.java
@@ -1,1586 +1,1586 @@
/*
Copyright (c) 2012, Mushroom Hostage
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package me.exphc.EnchantMore;
import java.util.Random;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.UUID;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Formatter;
import java.lang.Byte;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.event.entity.*;
import org.bukkit.Material.*;
import org.bukkit.material.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.command.*;
import org.bukkit.inventory.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.scheduler.*;
import org.bukkit.enchantments.*;
import org.bukkit.util.*;
import org.bukkit.*;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.craftbukkit.entity.CraftArrow;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.entity.CraftSpider;
import org.bukkit.craftbukkit.entity.CraftCaveSpider;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.craftbukkit.CraftWorld;
import net.minecraft.server.MobEffect;
import net.minecraft.server.MobEffectList;
import net.minecraft.server.FurnaceRecipes;
import net.minecraft.server.ItemDye;
//import net.minecraft.server.ItemStack; // import conflict
import net.minecraft.server.EntityArrow;
import net.minecraft.server.EnumSkyBlock;
class EnchantMoreListener implements Listener {
// Better enchantment names more closely matching in-game display
// TODO: replace with ItemStackX
final static Enchantment PROTECTION = Enchantment.PROTECTION_ENVIRONMENTAL;
final static Enchantment FIRE_PROTECTION = Enchantment.PROTECTION_FIRE;
final static Enchantment FEATHER_FALLING = Enchantment.PROTECTION_FALL;
final static Enchantment BLAST_PROTECTION = Enchantment.PROTECTION_EXPLOSIONS;
final static Enchantment PROJECTILE_PROTECTION = Enchantment.PROTECTION_PROJECTILE;
final static Enchantment RESPIRATION = Enchantment.OXYGEN;
final static Enchantment AQUA_AFFINITY = Enchantment.WATER_WORKER;
final static Enchantment SHARPNESS = Enchantment.DAMAGE_ALL;
final static Enchantment SMITE = Enchantment.DAMAGE_UNDEAD;
final static Enchantment BANE = Enchantment.DAMAGE_ARTHROPODS;
final static Enchantment KNOCKBACK = Enchantment.KNOCKBACK;
final static Enchantment FIRE_ASPECT = Enchantment.FIRE_ASPECT;
final static Enchantment LOOTING = Enchantment.LOOT_BONUS_MOBS;
final static Enchantment EFFICIENCY = Enchantment.DIG_SPEED;
final static Enchantment SILK_TOUCH = Enchantment.SILK_TOUCH;
final static Enchantment UNBREAKING = Enchantment.DURABILITY;
final static Enchantment FORTUNE = Enchantment.LOOT_BONUS_BLOCKS;
final static Enchantment POWER = Enchantment.ARROW_DAMAGE;
final static Enchantment PUNCH = Enchantment.ARROW_KNOCKBACK;
final static Enchantment FLAME = Enchantment.ARROW_FIRE;
final static Enchantment INFINITE = Enchantment.ARROW_INFINITE;
static Random random;
EnchantMore plugin;
public EnchantMoreListener(EnchantMore pl) {
plugin = pl;
random = new Random();
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
ItemStack item = event.getItem();
Action action = event.getAction();
Player player = event.getPlayer();
if (item == null) {
return;
}
final World world = player.getWorld();
// Actions not requiring a block
if (item.getType() == Material.BOW && (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)) {
// Bow + Efficiency = instant shoot
if (item.containsEnchantment(EFFICIENCY)) {
player.shootArrow();
}
} else if (isSword(item.getType())) {
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
// Sword + Power = strike lightning 100+ meters away
if (item.containsEnchantment(POWER)) {
int maxDistance = 100; // TODO: configurable
Block target = player.getTargetBlock(null, maxDistance * item.getEnchantmentLevel(FLAME));
if (target != null) {
world.strikeLightning(target.getLocation());
}
}
} /*else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
// TODO: Sword + Blast Protection = blocking summons summon fireballs
if (item.containsEnchantment(BLAST_PROTECTION)) {
// http://forums.bukkit.org/threads/summoning-a-fireball.40724/#post-738436
Location loc = event.getPlayer().getLocation();
Block b = event.getPlayer().getTargetBlock(null, 100 * item.getEnchantmentLevel(BLAST_PROTECTION));
if (b != null) {
Location target = b.getLocation();
Location from = lookAt(loc, target);
Entity fireball = from.getWorld().spawn(from, Fireball.class);
fireball.setVelocity(new Vector(0, -1, 0)); // TODO
} else {
plugin.log.info("no target?");
}
}
}*/
// TODO: Aqua Affinity = slowness
} else if (isShovel(item.getType())) {
// Shovel + Silk Touch II = harvest fire (secondary)
if (item.containsEnchantment(SILK_TOUCH) && item.getEnchantmentLevel(SILK_TOUCH) >= 2 &&
(action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK)) {
Block target = player.getTargetBlock(null, 3 * item.getEnchantmentLevel(SILK_TOUCH));
if (target.getType() == Material.FIRE) {
world.dropItemNaturally(target.getLocation(), new ItemStack(target.getType(), 1));
}
}
}
if (block == null) {
return;
}
// Everything else below requires a block
if (item.getType() == Material.SHEARS) {
// Shears + Power = cut grass (secondary effect)
if (item.containsEnchantment(POWER)) {
if (block.getType() == Material.GRASS) {
block.setType(Material.DIRT);
}
damage(item);
}
} else if (item.getType() == Material.FLINT_AND_STEEL && action == Action.RIGHT_CLICK_BLOCK) {
// Flint & Steel + Smite = strike lightning ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/8-fishing-rod-smite-strike-lightning/))
if (item.containsEnchantment(SMITE)) {
world.strikeLightning(block.getLocation());
damage(item, 9);
}
// Flint & Steel + Fire Protection = fire resistance ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/10-flint-steel-fire-protection-fire-resistance/))
if (item.containsEnchantment(FIRE_PROTECTION)) {
applyPlayerEffect(player, EFFECT_FIRE_RESISTANCE, item.getEnchantmentLevel(FIRE_PROTECTION));
// no extra damage
}
// Flint & Steel + Aqua Affinity = vaporize water ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/9-flint-steel-aqua-affinity-vaporize-water/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// Find water within ignited cube area
int r = item.getEnchantmentLevel(AQUA_AFFINITY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dy = -r; dy <= r; dy += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, dy+y0, dz+z0);
if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) {
b.setType(Material.AIR);
world.playEffect(b.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
}
}
}
// no extra damage
}
// Flint & Steel + Sharpness = fiery explosion
if (item.containsEnchantment(SHARPNESS)) {
float power = (item.getEnchantmentLevel(SHARPNESS) - 1) * 1.0f;
world.createExplosion(block.getLocation(), power, true);
damage(item);
}
// Flint & Steel + Efficiency = burn faster (turn wood to grass)
if (item.containsEnchantment(EFFICIENCY)) {
if (isWoodenBlock(block.getType(), block.getData())) {
block.setType(Material.LEAVES);
// TODO: data? just leaving as before, but type may be unexpected
}
// no extra damage
}
} else if (isHoe(item.getType())) {
// Hoe + Aqua Affinity = auto-hydrate ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/11-hoe-aqua-affinity-auto-hydrate/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// As long as not in hell, hydrate nearby
if (world.getEnvironment() != World.Environment.NETHER) {
int n = item.getEnchantmentLevel(AQUA_AFFINITY);
// Change adjacent air blocks to water
for (int dx = -1; dx <= 1; dx += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
Block near = block.getRelative(dx * n, 0, dz * n);
// if either air or flowing water, make stationary water
if (near.getType() == Material.AIR || near.getType() == Material.WATER) {
near.setType(Material.STATIONARY_WATER);
}
}
}
} else {
world.playEffect(block.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
// If soil, moisten thoroughly
// This works in The Nether, though it does not add water and will dry out eventually
if (block.getType() == Material.SOIL) {
block.setData((byte)8);
}
damage(item);
}
// Hoe + Fortune = chance to drop seeds
if (item.containsEnchantment(FORTUNE) && action == Action.RIGHT_CLICK_BLOCK) {
if (block.getType() == Material.DIRT || block.getType() == Material.GRASS) {
if (random.nextInt(2) != 0) { // TODO: configurable, and depend on level
Material seedType;
// TODO: configurable probabilities
switch (random.nextInt(4)) {
case 2: seedType = Material.MELON_SEEDS; break;
case 3: seedType = Material.PUMPKIN_SEEDS; break;
default: seedType = Material.SEEDS; // wheat, 50%
}
// TODO: configurable and random quantity
ItemStack drop = new ItemStack(seedType, 1);
world.dropItemNaturally(block.getRelative(BlockFace.UP).getLocation(), drop);
}
// no extra damage
}
}
// Hoe + Efficiency = till larger area
if (item.containsEnchantment(EFFICIENCY)) { // also can use left-click, for efficiency!
int r = item.getEnchantmentLevel(EFFICIENCY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, y0, dz+z0);
if (b.getType() == Material.DIRT || b.getType() == Material.GRASS) {
b.setType(Material.SOIL);
}
}
}
damage(item);
}
// Hoe + Respiration = grow ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/12-hoe-respiration-grow/))
// Note, left-click will also destroy sensitive plants (wheat, saplings, though interestingly not shrooms),
// so it will only work on blocks like grass (which does not break instantly). For
// this reason, also allow right-click for grow, even though it means you cannot till.
if (item.containsEnchantment(RESPIRATION)) {
growStructure(block.getLocation(), player);
damage(item);
// no need to cancel?
//event.setCancelled(true);
}
} else if (isPickaxe(item.getType())) {
// Pickaxe + Power = instantly break anything (including bedrock)
if (item.containsEnchantment(POWER)) {
// Note: this also works for bedrock!
block.breakNaturally(item);
- }
- damage(item);
+ damage(item);
+ }
}
}
// Use up a tool
public static void damage(ItemStack tool) {
damage(tool, 1);
}
public static void damage(ItemStack tool, int amount) {
tool.setDurability((short)(tool.getDurability() + amount));
// TODO: if reaches max, break? set to air or not?
}
/*
// Aim function
// see http://forums.bukkit.org/threads/summoning-a-fireball.40724/#post-738436
public static Location lookAt(Location from, Location to) {
Location loc = from.clone();
double dx = to.getX() - from.getX();
double dy = to.getY() - from.getY();
double dz = to.getZ() - from.getZ();
if (dx != 0) {
if (dx < 0) {
loc.setYaw((float)(1.5 * Math.PI));
} else {
loc.setYaw((float)(0.5 * Math.PI));
}
loc.setYaw((float)loc.getYaw() - (float)Math.atan(dz / dx));
} else if (dz < 0) {
loc.setYaw((float)Math.PI);
}
double dxz = Math.sqrt(dx * dx + dz * dz);
loc.setPitch((float)-Math.atan(dy / dxz));
loc.setYaw(-loc.getYaw() * 180f / (float)Math.PI);
loc.setPitch(loc.getPitch() * 180f / (float)Math.PI);
return loc;
}*/
// Attempt to grow organic structure
private void growStructure(Location loc, Player player) {
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
World world = loc.getWorld();
// Use bonemeal (white dye/ink) to grow
CraftItemStack bonemealStack = (new CraftItemStack(Material.INK_SACK, 1, (short)15));
// 'a' unobfuscated = onItemUse
net.minecraft.server.Item.INK_SACK.a(bonemealStack.getHandle(), ((CraftPlayer)player).getHandle(), ((CraftWorld)world).getHandle(), x, y, z, 0/*unused*/);
}
public static boolean isHoe(Material m) {
return m == Material.DIAMOND_HOE ||
m == Material.GOLD_HOE ||
m == Material.IRON_HOE ||
m == Material.STONE_HOE ||
m == Material.WOOD_HOE;
}
public static boolean isSword(Material m) {
return m == Material.DIAMOND_SWORD ||
m == Material.GOLD_SWORD ||
m == Material.IRON_SWORD ||
m == Material.STONE_SWORD ||
m == Material.WOOD_SWORD;
}
public static boolean isPickaxe(Material m) {
return m == Material.DIAMOND_PICKAXE ||
m == Material.GOLD_PICKAXE ||
m == Material.IRON_PICKAXE ||
m == Material.STONE_PICKAXE ||
m == Material.WOOD_PICKAXE;
}
public static boolean isShovel(Material m) {
return m == Material.DIAMOND_SPADE ||
m == Material.GOLD_SPADE ||
m == Material.IRON_SPADE ||
m == Material.STONE_SPADE ||
m == Material.WOOD_SPADE;
}
public static boolean isAxe(Material m) {
return m == Material.DIAMOND_AXE ||
m == Material.GOLD_AXE ||
m == Material.IRON_AXE ||
m == Material.STONE_AXE ||
m == Material.WOOD_AXE;
}
// Get whether material is a farm-related block, either land or growing crops
public static boolean isFarmBlock(Material m) {
return m == Material.SOIL || // Farmland
m == Material.CROPS || // wheat TODO: update wiki, calls 'Wheat Seeds' though in-game 'Crops'
m == Material.SUGAR_CANE_BLOCK ||
m == Material.CAKE_BLOCK ||
m == Material.PUMPKIN_STEM ||
m == Material.MELON_STEM ||
m == Material.NETHER_WARTS; // not the item, that is NETHER_STALK (confusingly)
}
// Get whether able to be excavated by shovel
public static boolean isExcavatable(int m) {
return m == Material.DIRT.getId() ||
m == Material.GRASS.getId() ||
m == Material.GRAVEL.getId() ||
m == Material.SOUL_SAND.getId() ||
m == Material.NETHERRACK.getId(); // not normally diggable, but why not?
}
public static boolean isExcavatable(Material m) {
return isExcavatable(m.getId());
}
// Return whether is a wooden block
public static boolean isWoodenBlock(Material m, byte data) {
return m == Material.WOOD ||
m == Material.WOOD_PLATE ||
m == Material.WOOD_STAIRS ||
m == Material.WOODEN_DOOR ||
m == Material.LOG ||
(m == Material.STEP && data == 2) || // wooden slab
(m == Material.DOUBLE_STEP && data == 2);// wooden double slab
}
// http://wiki.vg/Protocol#Effects
private static final int EFFECT_MOVE_SPEED = 1;
private static final int EFFECT_MOVE_SLOW_DOWN = 2;
private static final int EFFECT_DIG_SPEED = 3;
private static final int EFFECT_DIG_SLOW_DOWN = 4;
private static final int EFFECT_DAMAGE_BOOST = 5;
private static final int EFFECT_HEAL = 6;
private static final int EFFECT_HARM = 7;
private static final int EFFECT_JUMP = 8;
private static final int EFFECT_CONFUSION = 9;
private static final int EFFECT_REGENERATION = 10;
private static final int EFFECT_RESISTANCE = 11;
private static final int EFFECT_FIRE_RESISTANCE = 12;
private static final int EFFECT_WATER_BREATHING = 13;
private static final int EFFECT_INVISIBILITY = 14; // sadly, no effect in 1.1
private static final int EFFECT_BLINDNESS = 15;
private static final int EFFECT_NIGHTVISION = 16; // sadly, no effect in 1.1
private static final int EFFECT_HUNGER = 17;
private static final int EFFECT_WEAKNESS = 18;
private static final int EFFECT_POISON = 19;
private void applyPlayerEffect(Player player, int effect, int level) {
((CraftPlayer)player).getHandle().addEffect(new net.minecraft.server.MobEffect(
effect, // http://wiki.vg/Protocol#Effects
20 * 10 * level, // duration in ticks
1)); // amplifier
// TODO: can we used the predefined effects (w/ duration, amplifier) in MobEffectList?
// as suggested here: http://forums.bukkit.org/threads/potion-events.57086/#post-936679
// however, b() takes a MobEffect, but MobEffectList.CONFUSIOn is a MobEffectList
//(((CraftPlayer)entity).getHandle()).b(MobEffectList.CONFUSION);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Entity entity = event.getRightClicked();
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
if (item == null) {
return;
}
final World world = player.getWorld();
if (item.getType() == Material.FLINT_AND_STEEL) {
if (entity == null) {
return;
}
// Flint & Steel + Fire Aspect = set mobs on fire
if (item.containsEnchantment(FIRE_ASPECT)) {
entity.setFireTicks(getFireTicks(item.getEnchantmentLevel(FIRE_ASPECT)));
damage(item);
// Flint & Steel + Fire Protection = player fire resistance (secondary)
// We apply this for lighting blocks, too; this one is for attacking mobs
if (item.containsEnchantment(FIRE_PROTECTION)) {
applyPlayerEffect(player, EFFECT_FIRE_RESISTANCE, item.getEnchantmentLevel(FIRE_PROTECTION));
// no extra damage
}
}
// Flint & Steel + Respiration = smoke inhalation (confusion effect on player)
if (item.containsEnchantment(RESPIRATION)) {
world.playEffect(entity.getLocation(), Effect.SMOKE, 0); // TOOD: smoke direction
world.playEffect(entity.getLocation(), Effect.EXTINGUISH, 0); // TOOD: smoke direction
// Confusion effect on players
if (entity instanceof CraftPlayer) {
applyPlayerEffect((CraftPlayer)entity, EFFECT_CONFUSION, item.getEnchantmentLevel(RESPIRATION));
damage(item);
}
}
} else if (item.getType() == Material.SHEARS) {
// Shears + Smite = gouge eyes (blindness effect on player)
if (item.containsEnchantment(SMITE)) {
if (entity instanceof CraftPlayer) {
applyPlayerEffect((CraftPlayer)entity, EFFECT_BLINDNESS, item.getEnchantmentLevel(SMITE));
damage(item);
}
}
// Shears + Bane of Arthropods = collect spider eyes
if (item.containsEnchantment(BANE)) {
if (entity instanceof CaveSpider || entity instanceof Spider) {
Creature bug = (Creature)entity;
// If at least 50% health, cut out eyes, then drop health
if (bug.getHealth() >= bug.getMaxHealth() / 2) {
world.dropItemNaturally(bug.getEyeLocation(), new ItemStack(Material.SPIDER_EYE, 1));
bug.setHealth(bug.getMaxHealth() / 2 - 1);
}
damage(item);
}
}
// Shears + Looting = feathers from chicken (secondary)
if (item.containsEnchantment(LOOTING)) {
if (entity instanceof Chicken) {
Creature bird = (Creature)entity;
// Pulling feathers damages the creature
if (bird.getHealth() >= bird.getMaxHealth() / 2) {
world.dropItemNaturally(entity.getLocation(), new ItemStack(Material.FEATHER, random.nextInt(5) + 1));
bird.setHealth(bird.getMaxHealth() / 2 - 1);
// There isn't any "featherless chicken" sprite
}
damage(item);
}
}
} else if (isSword(item.getType())) {
/*
// BLOCKED: Sword + ? = night vision when blocking
// The visual effect plays (navy blue swirly particles), but doesn't actually do anything as of Minecraft 1.1
if (item.containsEnchantment(FLAME)) {
applyPlayerEffect(player, EFFECT_NIGHT_VISION, item.getEnchantmentLevel(FLAME));
damage(item);
}
// BLOCKED: Sword + Infinity = invisibility when blocking
// Also has no implemented effect in Minecraft 1.1. Maybe a plugin could use?
// TODO: use Vanish API in dev builts of Bukkit, that VanishNoPacket uses
if (item.containsEnchantment(INFINITE)) {
applyPlayerEffect(player, EFFECT_INVISIBILITY, item.getEnchantmentLevel(INFINITE));
damage(item);
}
*/
// Sword + Protection = resistance when blocking
if (item.containsEnchantment(PROTECTION)) {
applyPlayerEffect(player, EFFECT_RESISTANCE, item.getEnchantmentLevel(PROTECTION));
damage(item);
}
}
}
// Get time to burn entity for given enchantment level
private int getFireTicks(int level) {
// TODO: configurable ticks per level
return 20 * 10 * level;
}
// Break all contiguous blocks of the same type
private int breakContiguous(Block start, ItemStack tool, int limit) {
Set<Block> result = new HashSet<Block>();
plugin.log.info("collectContiguous starting");
collectContiguous(start, limit, result);
plugin.log.info("collectContiguous returned with "+result.size());
for (Block block: result) {
// TODO: accumulate same type to optimize drops?
//drops.addAll(block.getDrops(tool));
//block.setType(Material.AIR);
block.breakNaturally(tool); // no, infinite recurse
//plugin.log.info("break"+block);
}
return result.size();
}
// Recursively find all contiguous blocks
// TODO: faster?
private void collectContiguous(Block start, int limit, Set<Block> result) {
if (limit < 0) {
return;
}
result.add(start);
for (int dx = -1; dx <= 1; dx += 1) {
for (int dy = -1; dy <= 1; dy += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
if (dx == 0 && dy == 0 && dz == 0) {
continue;
}
Block other = start.getRelative(dx, dy, dz);
limit -= 1;
if (limit < 0) {
return;
}
// Follow same type _and_ data (different leaves, etc.)
if (other.getType() == start.getType() && other.getData() == start.getData()) {
collectContiguous(other, limit - 1, result);
}
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block block = event.getBlock();
ItemStack item = player.getItemInHand();
final World world = player.getWorld();
if (item == null) {
return;
}
if (isPickaxe(item.getType()) ||
isShovel(item.getType()) ||
isAxe(item.getType())) {
// Pickaxe + Flame = auto-smelt ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/2-pickaxe-shovel-axe-flame-auto-smelt/))
// Shovel + Flame = auto-smelt ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/2-pickaxe-shovel-axe-flame-auto-smelt/))
// Axe + Flame = auto-smelt ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/2-pickaxe-shovel-axe-flame-auto-smelt/))
if (item.containsEnchantment(FLAME)) {
Collection<ItemStack> rawDrops = block.getDrops(item);
for (ItemStack rawDrop: rawDrops) {
// note: original smelted idea from Firelord tools http://dev.bukkit.org/server-mods/firelord/
// also see Superheat plugin? either way, coded this myself..
ItemStack smeltedDrop = smelt(rawDrop);
if (smeltedDrop != null && smeltedDrop.getType() != Material.AIR) {
world.dropItemNaturally(block.getLocation(), smeltedDrop);
}
}
block.setType(Material.AIR);
// no extra damage
}
if (isAxe(item.getType())) {
// Axe + Power = fell tree ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/3-axe-power-fell-tree/))
if (item.containsEnchantment(POWER) && block.getType() == Material.LOG) {
// Chop tree
breakContiguous(block, item, 100 * item.getEnchantmentLevel(POWER));
// no extra damage
}
}
if (isShovel(item.getType())) {
// Shovel + Power = excavation (dig large area, no drops)
if (item.containsEnchantment(POWER) && isExcavatable(block.getType())) {
// Clear out those annoying veins of gravel (or dirt)
// too slow
//breakContiguous(block, item, 100 * item.getEnchantmentLevel(POWER));
// Dig a cube out, but no drops
int r = item.getEnchantmentLevel(POWER);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dy = -r; dy <= r; dy += 1) {
for (int dz = -r; dz <= r; dz += 1) {
int x = dx + x0, y = dy + y0, z = dz + z0;
int type = world.getBlockTypeIdAt(x, y, z);
if (isExcavatable(type)) {
Block b = world.getBlockAt(x, y, z);
b.setType(Material.AIR);
}
}
}
}
// no extra damage
}
// Shovel + Silk Touch II = harvest fallen snow, fire
// (fire elsewhere)
if (item.containsEnchantment(SILK_TOUCH) && item.getEnchantmentLevel(SILK_TOUCH) >= 2) {
if (block.getType() == Material.SNOW) {
world.dropItemNaturally(block.getLocation(), new ItemStack(block.getType(), 1));
block.setType(Material.AIR);
event.setCancelled(true); // do not drop snowballs
}
}
}
// Pickaxe + Silk Touch II = harvest ice
if (isPickaxe(item.getType())) {
if (item.containsEnchantment(SILK_TOUCH) && item.getEnchantmentLevel(SILK_TOUCH) >= plugin.getConfig().getInt("pickaxeSilkTouchIceLevel", 2)) {
if (block.getType() == Material.ICE) {
world.dropItemNaturally(block.getLocation(), new ItemStack(block.getType(), 1));
block.setType(Material.AIR);
// TODO craftbukkit 1.1-R3+MLP+MCF+IC2+BC2+RP2 NPE: at net.minecraft.server.ItemInWorldManager.breakBlock(ItemInWorldManager.java:254)
// if we don't do this, so do it
event.setCancelled(true);
// no extra damage
}
}
}
} else if (item.getType() == Material.SHEARS) {
// Shears + Silk Touch = collect cobweb, dead bush
if (item.containsEnchantment(SILK_TOUCH)) {
// Note: you can collect dead bush with shears on 12w05a!
// http://www.reddit.com/r/Minecraft/comments/pc2rs/just_noticed_dead_bush_can_be_collected_with/
if (block.getType() == Material.DEAD_BUSH ||
block.getType() == Material.WEB) {
world.dropItemNaturally(block.getLocation(), new ItemStack(block.getType(), 1));
block.setType(Material.AIR);
}
// no extra damage
}
// Shears + Fortune = apples from leaves
if (item.containsEnchantment(FORTUNE)) {
if (block.getType() == Material.LEAVES) {
Material dropType;
// TODO: different probabilities, depending on level too (higher, more golden)
switch (random.nextInt(10)) {
case 0: dropType = Material.GOLDEN_APPLE; break;
default: dropType = Material.APPLE;
}
world.dropItemNaturally(block.getLocation(), new ItemStack(dropType, 1));
block.setType(Material.AIR);
}
// no extra damage
}
// Shears + Power = hedge trimmer; cut grass
// see also secondary effect above
if (item.containsEnchantment(POWER) && block.getType() == Material.LEAVES) {
breakContiguous(block, item, 50 * item.getEnchantmentLevel(POWER));
// no extra damage
}
} else if (isHoe(item.getType())) {
// Hoe + Silk Touch = collect farmland, crop block, pumpkin/melon stem, cake block, sugarcane block, netherwart block (preserving data)
if (item.containsEnchantment(SILK_TOUCH)) {
// Collect farm-related blocks, preserving the growth/wetness/eaten data
if (isFarmBlock(block.getType())) {
ItemStack drop = new ItemStack(block.getType(), 1);
// Store block data value
//drop.setDurability(block.getData()); // bukkit doesn't preserve
drop.addUnsafeEnchantment(SILK_TOUCH, block.getData());
world.dropItemNaturally(block.getLocation(), drop);
block.setType(Material.AIR);
}
// no extra damage
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockPlace(BlockPlaceEvent event) {
Block block = event.getBlockPlaced();
World world = block.getWorld();
Player player = event.getPlayer();
// Item to place as a block
// NOT event.getItemInHand(), see https://bukkit.atlassian.net/browse/BUKKIT-596 BlockPlaceEvent getItemInHand() loses enchantments
ItemStack item = player.getItemInHand();
// Set data of farm-related block
if (item != null && item.containsEnchantment(SILK_TOUCH)) {
if (isFarmBlock(item.getType())) {
plugin.log.info("data"+item.getEnchantmentLevel(SILK_TOUCH));
// broken in 1.1-R2??
// TODO
block.setData((byte)item.getEnchantmentLevel(SILK_TOUCH));
}
}
if (block != null && block.getType() == Material.ICE) {
if (world.getEnvironment() == World.Environment.NETHER && plugin.getConfig().getBoolean("sublimateIce", false)) {
// sublimate ice to vapor
block.setType(Material.AIR);
// turn into smoke
world.playEffect(block.getLocation(), Effect.SMOKE, 0);
// Workaround type not changing, until fix is in a build:
// "Allow plugins to change ID and Data during BlockPlace event." Fixes BUKKIT-674
// https://github.com/Bukkit/CraftBukkit/commit/f29b84bf1579cf3af31ea3be6df0bc8917c1de0b
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new EnchantMoreAirTask(block));
}
}
}
// Get item as if it was smelted
private ItemStack smelt(ItemStack raw) {
net.minecraft.server.ItemStack smeltNMS = net.minecraft.server.FurnaceRecipes.getInstance().a(raw.getTypeId());
ItemStack smelted = (ItemStack)(new CraftItemStack(smeltNMS));
return smelted;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerShearEntity(PlayerShearEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getEntity();
ItemStack tool = player.getItemInHand();
final World world = player.getWorld();
if (tool == null) {
return;
}
if (!(entity instanceof Sheep)) {
return;
}
// TODO: mooshroom?
// Shears + Looting = more wool (random colors); feathers from chickens
// see also secondary effect above
if (tool.getType() == Material.SHEARS && tool.containsEnchantment(LOOTING)) {
Location loc = entity.getLocation();
int quantity = random.nextInt(tool.getEnchantmentLevel(LOOTING) * 2);
for (int i = 0; i < quantity; i += 1) {
short color = (short)random.nextInt(16);
world.dropItemNaturally(entity.getLocation(), new ItemStack(Material.WOOL, 1, color));
}
// no extra damage
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onProjectileHit(ProjectileHitEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Arrow)) {
return;
}
Arrow arrow = (Arrow)entity;
LivingEntity shooter = arrow.getShooter();
if (shooter == null || !(shooter instanceof Player)) {
// shot from dispenser, skeleton, etc.
return;
}
Player player = (Player)shooter;
ItemStack item = player.getItemInHand();
if (item == null || item.getType() != Material.BOW) {
return;
}
Location dest = arrow.getLocation();
final World world = dest.getWorld();
// Bow + Looting = steal ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/6-bow-looting-steal/))
if (item.containsEnchantment(LOOTING)) {
double s = 5.0 * item.getEnchantmentLevel(LOOTING);
List<Entity> loots = arrow.getNearbyEntities(s, s, s);
for (Entity loot: loots) {
// TODO: different levels, for only items, exp, mobs?
// This moves everything!
loot.teleport(player.getLocation());
}
}
// Bow + Smite = strike lightning
if (item.containsEnchantment(SMITE)) {
world.strikeLightning(dest);
}
// Bow + Fire Aspect = fiery explosions ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/5-bow-fire-aspect-fiery-explosions/))
if (item.containsEnchantment(FIRE_ASPECT)) {
float power = 1.0f * item.getEnchantmentLevel(FIRE_ASPECT);
world.createExplosion(dest, power, true);
}
// Bow + Aqua Affinity = freeze water, stun players
if (item.containsEnchantment(AQUA_AFFINITY)) {
int r = item.getEnchantmentLevel(AQUA_AFFINITY);
// freeze water
int x0 = dest.getBlockX();
int y0 = dest.getBlockY();
int z0 = dest.getBlockZ();
// TODO: refactor
for (int dx = -r; dx <= r; dx += 1) {
for (int dy = -r; dy <= r; dy += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, dy+y0, dz+z0);
if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) {
b.setType(Material.ICE);
}
}
}
}
// TODO: only poison hit player!
// stun nearby players
List<Entity> victims = arrow.getNearbyEntities(r, r, r);
for (Entity victim: victims) {
if (victim instanceof CraftPlayer) {
applyPlayerEffect((CraftPlayer)victim, EFFECT_MOVE_SLOW_DOWN, r);
}
}
// no extra damage
}
// Bow + Knockback = pierce blocks
if (item.containsEnchantment(KNOCKBACK)) {
class ArrowPierceTask implements Runnable {
Arrow arrow;
int depth;
public ArrowPierceTask(Arrow arrow, int depth) {
this.arrow = arrow;
this.depth = depth;
}
public void run() {
Vector velocity = arrow.getVelocity().clone(); // TODO: unit vector?
Block block = getArrowHit(arrow);
if (block.getType() == Material.BEDROCK) {
return; // bad news
}
// TODO: factor in hardness of material somehow?
// Pierce block, destroying it
block.setType(Material.AIR);
// TODO: should it drop items?
// Trace through multiple blocks in same direction, up to enchantment level
if (depth > 1) {
Vector start = new Vector(block.getLocation().getBlockX(), block.getLocation().getBlockY(), block.getLocation().getBlockZ());
BlockIterator it = new BlockIterator(world, start, velocity, 0, depth);
while (it.hasNext()) {
Block b = it.next();
if (b.getType() != Material.BEDROCK) {
b.setType(Material.AIR);
// TODO: figure out how to refresh lighting here
//b.setData(b.getData(), true);
}
}
}
// if we don't remove, the arrow will fall down, then hit another
// block, and another..until it reaches bedrock!
arrow.remove();
}
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ArrowPierceTask(arrow, item.getEnchantmentLevel(KNOCKBACK)));
}
// TODO: phase, arrow through blocks
// TODO: fire protection = remove water (like flint & steel aqua affinity)
// Bow + Bane of Arthropods = poison
if (item.containsEnchantment(BANE)) {
// TODO: only poison hit player!
// poison nearby players
int r = item.getEnchantmentLevel(BANE);
List<Entity> victims = arrow.getNearbyEntities(r, r, r);
for (Entity victim: victims) {
if (victim instanceof CraftPlayer) {
applyPlayerEffect((CraftPlayer)victim, EFFECT_POISON, r);
}
}
}
// Bow + Feather Falling = teleport ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/4-bow-feather-falling-teleport/))
if (item.containsEnchantment(FEATHER_FALLING)) {
// use up the arrow (TODO: not at higher levels?) or set no pickup?
arrow.remove();
player.teleport(dest);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerFish(PlayerFishEvent event) {
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
if (item == null) {
return;
}
PlayerFishEvent.State state = event.getState();
World world = player.getWorld();
if (state == PlayerFishEvent.State.CAUGHT_ENTITY) {
Entity entity = event.getCaught();
if (entity == null) {
return;
}
// Fishing Rod + Fire Aspect = set mobs on fire
if (item.containsEnchantment(FIRE_ASPECT)) {
entity.setFireTicks(getFireTicks(item.getEnchantmentLevel(FIRE_ASPECT)));
damage(item);
}
// Fishing Rod + Smite = strike mobs with lightning
if (item.containsEnchantment(SMITE)) {
world.strikeLightning(entity.getLocation());
damage(item);
}
} else if (state == PlayerFishEvent.State.CAUGHT_FISH) {
// Fishing Rod + Flame = catch cooked fish
if (item.containsEnchantment(FLAME)) {
event.setCancelled(true);
// replace raw with cooked (TODO: play well with all other enchantments)
world.dropItemNaturally(player.getLocation(), new ItemStack(Material.COOKED_FISH, 1));
}
// Fishing Rod + Looting = catch extra fish
if (item.containsEnchantment(LOOTING)) {
// one extra per level
world.dropItemNaturally(player.getLocation(), new ItemStack(Material.RAW_FISH, item.getEnchantmentLevel(FORTUNE)));
}
// Fishing Rod + Fortune = catch junk ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/7-fishing-rod-fortune-catch-sunken-treasure/))
if (item.containsEnchantment(FORTUNE)) {
int quantity = item.getEnchantmentLevel(FORTUNE);
Material m;
// TODO: configurable, like Junkyard Creek http://dev.bukkit.org/server-mods/junkyardcreek/
switch(random.nextInt(19)) {
case 0: m = Material.MONSTER_EGGS; break; // hidden silverfish block
case 1:
default:
case 2: m = Material.DIRT; break;
case 3:
case 4: m = Material.WOOD; break;
case 5: m = Material.SPONGE; break;
case 6: m = Material.DEAD_BUSH; break;
case 7: m = Material.EYE_OF_ENDER; break;
case 8: m = Material.DIAMOND; break;
case 9:
case 10:
case 11: m = Material.IRON_INGOT; break;
case 12:
case 13: m = Material.GOLD_INGOT; break;
case 14: m = Material.CHAINMAIL_CHESTPLATE; break;
case 15:
case 16: m = Material.WATER_BUCKET; break;
case 17: m = Material.BOAT; break;
case 18: m = Material.SLIME_BALL; break;
case 19: m = Material.FERMENTED_SPIDER_EYE; break;
// TODO: leather boot
}
world.dropItemNaturally(player.getLocation(), new ItemStack(m, quantity));
// TODO: should also cancel fish event as to not drop?
}
// no extra damage
} else if (state == PlayerFishEvent.State.FAILED_ATTEMPT) {
// Fishing Rod + Silk Touch = catch more reliably
if (item.containsEnchantment(SILK_TOUCH)) {
// probability
// TODO: configurable levels, maybe to 100?
// 4 = always
int n = 4 - item.getEnchantmentLevel(SILK_TOUCH);
if (n < 1) {
n = 1;
}
if (random.nextInt(n) == 0) {
// TODO: integrate with Flame to catch cooked, too
world.dropItemNaturally(player.getLocation(), new ItemStack(Material.RAW_FISH, 1));
}
}
// no extra damage
} else if (state == PlayerFishEvent.State.FISHING) {
// Fishing Rod + Efficiency = fish faster
if (item.containsEnchantment(EFFICIENCY)) {
// 13 seconds for level 1, down to 1 for level 7
int delayTicks = (15 - item.getEnchantmentLevel(EFFICIENCY) * 2) * 20;
if (delayTicks < 0) {
delayTicks = 0;
}
// TODO: add some randomness
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new EnchantMoreFishTask(player, world), delayTicks);
// TODO: cancel task if stop fishing (change state)
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityShootBow(EntityShootBowEvent event) {
ItemStack bow = event.getBow();
if (bow == null) {
// shot by skeleton
return;
}
Entity projectile = event.getProjectile();
if (!(projectile instanceof Arrow)) {
return;
}
// Bow + Sharpness = increase velocity
if (bow.containsEnchantment(SHARPNESS)) {
double factor = 2.0 * bow.getEnchantmentLevel(SHARPNESS); // TODO: configurable factor
// TODO: instead of scalar multiplication, therefore also multiplying the 'shooting inaccuracy'
// offset, should we instead try to straighten out the alignment vector?
projectile.setVelocity(projectile.getVelocity().multiply(factor));
event.setProjectile(projectile);
}
}
// Get the block an arrow hit
// see http://forums.bukkit.org/threads/on-how-to-get-the-block-an-arrow-lands-in.55768/#post-954542
public Block getArrowHit(Arrow arrow) {
World world = arrow.getWorld();
net.minecraft.server.EntityArrow entityArrow = ((CraftArrow)arrow).getHandle();
try {
// saved to NBT tag as xTile,yTile,zTile
Field fieldX = net.minecraft.server.EntityArrow.class.getDeclaredField("e");
Field fieldY = net.minecraft.server.EntityArrow.class.getDeclaredField("f");
Field fieldZ = net.minecraft.server.EntityArrow.class.getDeclaredField("g");
fieldX.setAccessible(true);
fieldY.setAccessible(true);
fieldZ.setAccessible(true);
int x = fieldX.getInt(entityArrow);
int y = fieldY.getInt(entityArrow);
int z = fieldZ.getInt(entityArrow);
return world.getBlockAt(x, y, z);
} catch (Exception e) {
plugin.log.info("getArrowHit("+arrow+" reflection failed: "+e);
throw new IllegalArgumentException(e);
}
}
/*
// TODO: attempt to cancel burning when swimming in lava - no effect
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player)entity;
ItemStack helmet = player.getInventory().getHelmet();
if (helmet != null && helmet.containsEnchantment(FIRE_ASPECT)) {
event.setCancelled(true);
}
}*/
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player)entity;
ItemStack chestplate = player.getInventory().getChestplate();
// Chestplate + Infinity = god mode (no damage)
if (chestplate != null && chestplate.containsEnchantment(INFINITE)) {
// no damage ever
// TODO: also need to cancel death? can die elsewhere?
event.setCancelled(true);
}
EntityDamageEvent.DamageCause cause = event.getCause();
if (cause == EntityDamageEvent.DamageCause.LAVA ||
cause == EntityDamageEvent.DamageCause.FIRE ||
cause == EntityDamageEvent.DamageCause.FIRE_TICK) {
ItemStack helmet = player.getInventory().getHelmet();
// Helmet + Fire Aspect = swim in lava
if (helmet != null && helmet.containsEnchantment(FIRE_ASPECT)) {
event.setCancelled(true); // stop knockback and damage
//event.setDamage(0);
player.setFireTicks(0); // cool off immediately after exiting lava
// TODO: can we display air meter under lava?
/*
player.setMaximumAir(20*10);
player.setRemainingAir(20*10);
*/
// similar: http://dev.bukkit.org/server-mods/goldenchant/
// "golden chestplate = immunity to fire and lava damage" [like my Helmet with Fire Aspect]
// "golden helmet = breath underwater" [seems to overlap with Respiration, meh]
// "golden shoes = no fall damage" [ditto for Feather Falling]
}
}
if (event instanceof EntityDamageByEntityEvent) { // note: do not register directly
EntityDamageByEntityEvent e2 = (EntityDamageByEntityEvent)event;
Entity damager = e2.getDamager();
if (damager instanceof Arrow) { // TODO: all projectiles?
Arrow arrow = (Arrow)damager;
// Chestplate + Knockback = reflect arrows
if (chestplate != null && chestplate.containsEnchantment(KNOCKBACK)) {
event.setCancelled(true); // stop arrow damage
player.shootArrow(); // reflect arrow
// TODO: should we actually create a new arrow with the opposite velocity vector?
// I think so.. bounce, not reshoot
// not right
/*
Location location = player.getLocation();
World world = location.getWorld();
Vector velocity = arrow.getVelocity().multiply(-1);
float speed = 0.6f; // "A recommend speed is 0.6"
float spread = 12f; // "A recommend spread is 12"
world.spawnArrow(location, velocity, speed, spread);
*/
damage(chestplate);
}
// TODO: Sword + Projectile Protection = reflect arrows while blocking
// make it as ^^ is, nerf above (sword direction control, chestplate not)
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ItemStack item = player.getInventory().getItem(event.getNewSlot());
if (item != null && isSword(item.getType())) {
// Sword + Flame = create semi-permanent lit path
if (item.containsEnchantment(FLAME)) {
// Task to light up player, as long as its holding the right tool
class EnchantMoreFlameLightTask implements Runnable {
Player player;
EnchantMore plugin;
public EnchantMoreFlameLightTask(EnchantMore plugin, Player player) {
this.plugin = plugin;
this.player = player;
}
public void run() {
ItemStack item = player.getItemInHand();
if (item != null && EnchantMoreListener.isSword(item.getType())) {
if (item.containsEnchantment(EnchantMoreListener.FLAME)) {
Location to = player.getLocation();
World world = to.getWorld();
int x = to.getBlockX();
int y = to.getBlockY();
int z = to.getBlockZ();
// Light up player like a torch
// http://forums.bukkit.org/threads/make-a-player-light-up-like-they-are-a-torch.58749/#post-952252
// http://dev.bukkit.org/server-mods/head-lamp/
((CraftWorld)world).getHandle().a(net.minecraft.server.EnumSkyBlock.BLOCK, x, y+2, z, 15);
//((CraftWorld)world).getHandle().notify(x, y+2, z);
// Force update
Location below = new Location(world, x, y+1, z);
below.getBlock().setType(below.getBlock().getType());
below.getBlock().setData(below.getBlock().getData());
// Schedule another task to update again
// This won't be scheduled if they didn't have the right tool, so it'll die off
//plugin.log.info("LIT");
// Updates faster if higher level
int period = 20 * 2 / item.getEnchantmentLevel(EnchantMoreListener.FLAME);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new EnchantMoreFlameLightTask(plugin, player), period);
}
}
}
}
EnchantMoreFlameLightTask task = new EnchantMoreFlameLightTask(plugin, player);
// run once to kick off, it will re-schedule itself if appropriate
// (note need to schedule to run, so will run after item actually changes in hand)
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new EnchantMoreFlameLightTask(plugin, player));
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
ItemStack boots = player.getInventory().getBoots();
// Boots + Punch = shift to hover jump
if (boots != null && boots.containsEnchantment(PUNCH)) {
int n = boots.getEnchantmentLevel(PUNCH);
player.setVelocity(new Vector(0, n, 0));
}
}
}
// Task to efficiently drop fish after some time of fishing
class EnchantMoreFishTask implements Runnable {
Player player;
World world;
public EnchantMoreFishTask(Player p, World w) {
player = p;
world = w;
}
public void run() {
ItemStack tool = player.getItemInHand();
if (tool != null && tool.getType() == Material.FISHING_ROD) {
world.dropItemNaturally(player.getLocation(), new ItemStack(Material.RAW_FISH, 1));
EnchantMoreListener.damage(tool);
}
// TODO: reel in fishing line?
}
}
class EnchantMoreAirTask implements Runnable {
Block block;
public EnchantMoreAirTask(Block block) {
this.block = block;
}
public void run() {
block.setType(Material.AIR);
}
}
class EnchantMorePlayerMoveListener implements Listener {
EnchantMore plugin;
public EnchantMorePlayerMoveListener(EnchantMore plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
if (item == null) {
return;
}
// TODO: Boots + Efficiency = no slow down walking on soul sand, ice
// idea from http://dev.bukkit.org/server-mods/elemental-armor/
// how to speed up? or potion speed effect?
// http://forums.bukkit.org/threads/req-useful-gold-armor-read-first.59430/
// GoldenSprint? faster while sneaking? "feels too laggy" - listens to player move
// GoldenEnchant? "golden pants = super speed & flying while holding shift" for 1.8 beta
// also on player move, but if sprinting multiples velocity vector
// odd diamond block enchant deal
ItemStack boots = player.getInventory().getBoots();
if (boots != null) {
// Boots + Power = witch's broom (sprint flying)
if (boots.containsEnchantment(EnchantMoreListener.POWER)) {
if (player.isSprinting()) {
Vector velocity = event.getTo().getDirection().normalize().multiply(boots.getEnchantmentLevel(EnchantMoreListener.POWER));
// may get kicked for flying TODO: enable flying for user
player.setVelocity(velocity);
// TODO: mitigate? only launch once, so can't really fly, just a boost?
// TODO: setSprinting(false)
// cool down period?
// TODO: damage the boots? use up or infinite??
}
}
// Boots + Flame = firewalker (set ground on fire)
if (boots.containsEnchantment(EnchantMoreListener.FLAME)) {
Location to = event.getTo();
Location from = event.getFrom();
World world = from.getWorld();
// get from where coming from
int dx = from.getBlockX() - to.getBlockX();
int dz = from.getBlockZ() - to.getBlockZ();
// a few blocks behind, further if higher level
dx *= boots.getEnchantmentLevel(EnchantMoreListener.FLAME) + 1;
dz *= boots.getEnchantmentLevel(EnchantMoreListener.FLAME) + 1;
// if moved from block (try not to set player on fire)
if (dx != 0 || dz != 0) {
Block block = world.getBlockAt(from.getBlockX() + dx, to.getBlockY(), from.getBlockZ() + dz);
if (block.getType() == Material.AIR) {
block.setType(Material.FIRE);
}
}
// http://dev.bukkit.org/server-mods/firelord/ "The boots set the ground on fire!"
}
// TODO: Boots + Aqua Affinity = walk on water
/*
if (boots.containsEnchantment(EnchantMoreListener.AQUA_AFFINITY)) {
World world = event.getTo().getWorld();
Block block = event.getTo().getBlock();
if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) {
// why does this reset pitch/yaw?
//Location meniscus = new Location(world, event.getTo().getX(), block.getLocation().getY(), event.getTo().getZ());
//Location meniscus = new Location(world, event.getTo().getX(), event.getTo().getY(), event.getTo().getZ());
//event.setTo(meniscus);
// really annoying, keeps bouncing, can't move fast
event.setTo(event.getTo().clone().add(0, 0.1, 0));
}
// see also: God Powers jesus raft
// https://github.com/FriedTaco/godPowers/blob/master/godPowers/src/com/FriedTaco/taco/godPowers/Jesus.java
// creates a block underneath you, quite complex
}*/
// TODO: Boots + Knockback = bounce on fall
/*
if (boots.containsEnchantment(EnchantMoreListener.KNOCKBACK)) {
if (event.getTo().getY() < event.getFrom().getY()) {
Block block = event.getTo().getBlock();
Block land = block.getRelative(BlockFace.DOWN);
plugin.log.info("land="+land);
if (land.getType() != Material.AIR) {
int n = boots.getEnchantmentLevel(EnchantMoreListener.KNOCKBACK);
player.setVelocity(event.getPlayer().getVelocity().multiply(-n));
}
}
}
*/
}
}
}
public class EnchantMore extends JavaPlugin {
Logger log = Logger.getLogger("Minecraft");
public void onEnable() {
new EnchantMoreListener(this);
if (getConfig().getBoolean("moveListener", true)) {
new EnchantMorePlayerMoveListener(this);
}
}
public void onDisable() {
}
}
| false | true |
public void onPlayerInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
ItemStack item = event.getItem();
Action action = event.getAction();
Player player = event.getPlayer();
if (item == null) {
return;
}
final World world = player.getWorld();
// Actions not requiring a block
if (item.getType() == Material.BOW && (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)) {
// Bow + Efficiency = instant shoot
if (item.containsEnchantment(EFFICIENCY)) {
player.shootArrow();
}
} else if (isSword(item.getType())) {
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
// Sword + Power = strike lightning 100+ meters away
if (item.containsEnchantment(POWER)) {
int maxDistance = 100; // TODO: configurable
Block target = player.getTargetBlock(null, maxDistance * item.getEnchantmentLevel(FLAME));
if (target != null) {
world.strikeLightning(target.getLocation());
}
}
} /*else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
// TODO: Sword + Blast Protection = blocking summons summon fireballs
if (item.containsEnchantment(BLAST_PROTECTION)) {
// http://forums.bukkit.org/threads/summoning-a-fireball.40724/#post-738436
Location loc = event.getPlayer().getLocation();
Block b = event.getPlayer().getTargetBlock(null, 100 * item.getEnchantmentLevel(BLAST_PROTECTION));
if (b != null) {
Location target = b.getLocation();
Location from = lookAt(loc, target);
Entity fireball = from.getWorld().spawn(from, Fireball.class);
fireball.setVelocity(new Vector(0, -1, 0)); // TODO
} else {
plugin.log.info("no target?");
}
}
}*/
// TODO: Aqua Affinity = slowness
} else if (isShovel(item.getType())) {
// Shovel + Silk Touch II = harvest fire (secondary)
if (item.containsEnchantment(SILK_TOUCH) && item.getEnchantmentLevel(SILK_TOUCH) >= 2 &&
(action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK)) {
Block target = player.getTargetBlock(null, 3 * item.getEnchantmentLevel(SILK_TOUCH));
if (target.getType() == Material.FIRE) {
world.dropItemNaturally(target.getLocation(), new ItemStack(target.getType(), 1));
}
}
}
if (block == null) {
return;
}
// Everything else below requires a block
if (item.getType() == Material.SHEARS) {
// Shears + Power = cut grass (secondary effect)
if (item.containsEnchantment(POWER)) {
if (block.getType() == Material.GRASS) {
block.setType(Material.DIRT);
}
damage(item);
}
} else if (item.getType() == Material.FLINT_AND_STEEL && action == Action.RIGHT_CLICK_BLOCK) {
// Flint & Steel + Smite = strike lightning ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/8-fishing-rod-smite-strike-lightning/))
if (item.containsEnchantment(SMITE)) {
world.strikeLightning(block.getLocation());
damage(item, 9);
}
// Flint & Steel + Fire Protection = fire resistance ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/10-flint-steel-fire-protection-fire-resistance/))
if (item.containsEnchantment(FIRE_PROTECTION)) {
applyPlayerEffect(player, EFFECT_FIRE_RESISTANCE, item.getEnchantmentLevel(FIRE_PROTECTION));
// no extra damage
}
// Flint & Steel + Aqua Affinity = vaporize water ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/9-flint-steel-aqua-affinity-vaporize-water/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// Find water within ignited cube area
int r = item.getEnchantmentLevel(AQUA_AFFINITY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dy = -r; dy <= r; dy += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, dy+y0, dz+z0);
if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) {
b.setType(Material.AIR);
world.playEffect(b.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
}
}
}
// no extra damage
}
// Flint & Steel + Sharpness = fiery explosion
if (item.containsEnchantment(SHARPNESS)) {
float power = (item.getEnchantmentLevel(SHARPNESS) - 1) * 1.0f;
world.createExplosion(block.getLocation(), power, true);
damage(item);
}
// Flint & Steel + Efficiency = burn faster (turn wood to grass)
if (item.containsEnchantment(EFFICIENCY)) {
if (isWoodenBlock(block.getType(), block.getData())) {
block.setType(Material.LEAVES);
// TODO: data? just leaving as before, but type may be unexpected
}
// no extra damage
}
} else if (isHoe(item.getType())) {
// Hoe + Aqua Affinity = auto-hydrate ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/11-hoe-aqua-affinity-auto-hydrate/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// As long as not in hell, hydrate nearby
if (world.getEnvironment() != World.Environment.NETHER) {
int n = item.getEnchantmentLevel(AQUA_AFFINITY);
// Change adjacent air blocks to water
for (int dx = -1; dx <= 1; dx += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
Block near = block.getRelative(dx * n, 0, dz * n);
// if either air or flowing water, make stationary water
if (near.getType() == Material.AIR || near.getType() == Material.WATER) {
near.setType(Material.STATIONARY_WATER);
}
}
}
} else {
world.playEffect(block.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
// If soil, moisten thoroughly
// This works in The Nether, though it does not add water and will dry out eventually
if (block.getType() == Material.SOIL) {
block.setData((byte)8);
}
damage(item);
}
// Hoe + Fortune = chance to drop seeds
if (item.containsEnchantment(FORTUNE) && action == Action.RIGHT_CLICK_BLOCK) {
if (block.getType() == Material.DIRT || block.getType() == Material.GRASS) {
if (random.nextInt(2) != 0) { // TODO: configurable, and depend on level
Material seedType;
// TODO: configurable probabilities
switch (random.nextInt(4)) {
case 2: seedType = Material.MELON_SEEDS; break;
case 3: seedType = Material.PUMPKIN_SEEDS; break;
default: seedType = Material.SEEDS; // wheat, 50%
}
// TODO: configurable and random quantity
ItemStack drop = new ItemStack(seedType, 1);
world.dropItemNaturally(block.getRelative(BlockFace.UP).getLocation(), drop);
}
// no extra damage
}
}
// Hoe + Efficiency = till larger area
if (item.containsEnchantment(EFFICIENCY)) { // also can use left-click, for efficiency!
int r = item.getEnchantmentLevel(EFFICIENCY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, y0, dz+z0);
if (b.getType() == Material.DIRT || b.getType() == Material.GRASS) {
b.setType(Material.SOIL);
}
}
}
damage(item);
}
// Hoe + Respiration = grow ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/12-hoe-respiration-grow/))
// Note, left-click will also destroy sensitive plants (wheat, saplings, though interestingly not shrooms),
// so it will only work on blocks like grass (which does not break instantly). For
// this reason, also allow right-click for grow, even though it means you cannot till.
if (item.containsEnchantment(RESPIRATION)) {
growStructure(block.getLocation(), player);
damage(item);
// no need to cancel?
//event.setCancelled(true);
}
} else if (isPickaxe(item.getType())) {
// Pickaxe + Power = instantly break anything (including bedrock)
if (item.containsEnchantment(POWER)) {
// Note: this also works for bedrock!
block.breakNaturally(item);
}
damage(item);
}
}
|
public void onPlayerInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
ItemStack item = event.getItem();
Action action = event.getAction();
Player player = event.getPlayer();
if (item == null) {
return;
}
final World world = player.getWorld();
// Actions not requiring a block
if (item.getType() == Material.BOW && (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)) {
// Bow + Efficiency = instant shoot
if (item.containsEnchantment(EFFICIENCY)) {
player.shootArrow();
}
} else if (isSword(item.getType())) {
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
// Sword + Power = strike lightning 100+ meters away
if (item.containsEnchantment(POWER)) {
int maxDistance = 100; // TODO: configurable
Block target = player.getTargetBlock(null, maxDistance * item.getEnchantmentLevel(FLAME));
if (target != null) {
world.strikeLightning(target.getLocation());
}
}
} /*else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
// TODO: Sword + Blast Protection = blocking summons summon fireballs
if (item.containsEnchantment(BLAST_PROTECTION)) {
// http://forums.bukkit.org/threads/summoning-a-fireball.40724/#post-738436
Location loc = event.getPlayer().getLocation();
Block b = event.getPlayer().getTargetBlock(null, 100 * item.getEnchantmentLevel(BLAST_PROTECTION));
if (b != null) {
Location target = b.getLocation();
Location from = lookAt(loc, target);
Entity fireball = from.getWorld().spawn(from, Fireball.class);
fireball.setVelocity(new Vector(0, -1, 0)); // TODO
} else {
plugin.log.info("no target?");
}
}
}*/
// TODO: Aqua Affinity = slowness
} else if (isShovel(item.getType())) {
// Shovel + Silk Touch II = harvest fire (secondary)
if (item.containsEnchantment(SILK_TOUCH) && item.getEnchantmentLevel(SILK_TOUCH) >= 2 &&
(action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK)) {
Block target = player.getTargetBlock(null, 3 * item.getEnchantmentLevel(SILK_TOUCH));
if (target.getType() == Material.FIRE) {
world.dropItemNaturally(target.getLocation(), new ItemStack(target.getType(), 1));
}
}
}
if (block == null) {
return;
}
// Everything else below requires a block
if (item.getType() == Material.SHEARS) {
// Shears + Power = cut grass (secondary effect)
if (item.containsEnchantment(POWER)) {
if (block.getType() == Material.GRASS) {
block.setType(Material.DIRT);
}
damage(item);
}
} else if (item.getType() == Material.FLINT_AND_STEEL && action == Action.RIGHT_CLICK_BLOCK) {
// Flint & Steel + Smite = strike lightning ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/8-fishing-rod-smite-strike-lightning/))
if (item.containsEnchantment(SMITE)) {
world.strikeLightning(block.getLocation());
damage(item, 9);
}
// Flint & Steel + Fire Protection = fire resistance ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/10-flint-steel-fire-protection-fire-resistance/))
if (item.containsEnchantment(FIRE_PROTECTION)) {
applyPlayerEffect(player, EFFECT_FIRE_RESISTANCE, item.getEnchantmentLevel(FIRE_PROTECTION));
// no extra damage
}
// Flint & Steel + Aqua Affinity = vaporize water ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/9-flint-steel-aqua-affinity-vaporize-water/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// Find water within ignited cube area
int r = item.getEnchantmentLevel(AQUA_AFFINITY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dy = -r; dy <= r; dy += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, dy+y0, dz+z0);
if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) {
b.setType(Material.AIR);
world.playEffect(b.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
}
}
}
// no extra damage
}
// Flint & Steel + Sharpness = fiery explosion
if (item.containsEnchantment(SHARPNESS)) {
float power = (item.getEnchantmentLevel(SHARPNESS) - 1) * 1.0f;
world.createExplosion(block.getLocation(), power, true);
damage(item);
}
// Flint & Steel + Efficiency = burn faster (turn wood to grass)
if (item.containsEnchantment(EFFICIENCY)) {
if (isWoodenBlock(block.getType(), block.getData())) {
block.setType(Material.LEAVES);
// TODO: data? just leaving as before, but type may be unexpected
}
// no extra damage
}
} else if (isHoe(item.getType())) {
// Hoe + Aqua Affinity = auto-hydrate ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/11-hoe-aqua-affinity-auto-hydrate/))
if (item.containsEnchantment(AQUA_AFFINITY)) {
// As long as not in hell, hydrate nearby
if (world.getEnvironment() != World.Environment.NETHER) {
int n = item.getEnchantmentLevel(AQUA_AFFINITY);
// Change adjacent air blocks to water
for (int dx = -1; dx <= 1; dx += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
Block near = block.getRelative(dx * n, 0, dz * n);
// if either air or flowing water, make stationary water
if (near.getType() == Material.AIR || near.getType() == Material.WATER) {
near.setType(Material.STATIONARY_WATER);
}
}
}
} else {
world.playEffect(block.getLocation(), Effect.SMOKE, 0); // TODO: direction
}
// If soil, moisten thoroughly
// This works in The Nether, though it does not add water and will dry out eventually
if (block.getType() == Material.SOIL) {
block.setData((byte)8);
}
damage(item);
}
// Hoe + Fortune = chance to drop seeds
if (item.containsEnchantment(FORTUNE) && action == Action.RIGHT_CLICK_BLOCK) {
if (block.getType() == Material.DIRT || block.getType() == Material.GRASS) {
if (random.nextInt(2) != 0) { // TODO: configurable, and depend on level
Material seedType;
// TODO: configurable probabilities
switch (random.nextInt(4)) {
case 2: seedType = Material.MELON_SEEDS; break;
case 3: seedType = Material.PUMPKIN_SEEDS; break;
default: seedType = Material.SEEDS; // wheat, 50%
}
// TODO: configurable and random quantity
ItemStack drop = new ItemStack(seedType, 1);
world.dropItemNaturally(block.getRelative(BlockFace.UP).getLocation(), drop);
}
// no extra damage
}
}
// Hoe + Efficiency = till larger area
if (item.containsEnchantment(EFFICIENCY)) { // also can use left-click, for efficiency!
int r = item.getEnchantmentLevel(EFFICIENCY);
Location loc = block.getLocation();
int x0 = loc.getBlockX();
int y0 = loc.getBlockY();
int z0 = loc.getBlockZ();
for (int dx = -r; dx <= r; dx += 1) {
for (int dz = -r; dz <= r; dz += 1) {
Block b = world.getBlockAt(dx+x0, y0, dz+z0);
if (b.getType() == Material.DIRT || b.getType() == Material.GRASS) {
b.setType(Material.SOIL);
}
}
}
damage(item);
}
// Hoe + Respiration = grow ([screenshot](http://dev.bukkit.org/server-mods/enchantmore/images/12-hoe-respiration-grow/))
// Note, left-click will also destroy sensitive plants (wheat, saplings, though interestingly not shrooms),
// so it will only work on blocks like grass (which does not break instantly). For
// this reason, also allow right-click for grow, even though it means you cannot till.
if (item.containsEnchantment(RESPIRATION)) {
growStructure(block.getLocation(), player);
damage(item);
// no need to cancel?
//event.setCancelled(true);
}
} else if (isPickaxe(item.getType())) {
// Pickaxe + Power = instantly break anything (including bedrock)
if (item.containsEnchantment(POWER)) {
// Note: this also works for bedrock!
block.breakNaturally(item);
damage(item);
}
}
}
|
diff --git a/src/main/java/me/furt/industrial/block/BlockMiningMachine.java b/src/main/java/me/furt/industrial/block/BlockMiningMachine.java
index bcd400d..a0e0226 100644
--- a/src/main/java/me/furt/industrial/block/BlockMiningMachine.java
+++ b/src/main/java/me/furt/industrial/block/BlockMiningMachine.java
@@ -1,15 +1,15 @@
package me.furt.industrial.block;
import me.furt.industrial.IndustrialInc;
import me.furt.industrial.block.design.DesignGenericBlock;
import org.getspout.spoutapi.material.block.GenericCubeCustomBlock;
public class BlockMiningMachine extends GenericCubeCustomBlock {
public BlockMiningMachine(IndustrialInc plugin) {
super(plugin, "Mining Machine", new DesignGenericBlock(plugin,
- plugin.assets.getTexture("block_machine"), new int[] { 103, 40,
- 40, 40, 40, 24 }));
+ plugin.assets.getTexture("block_machine"), new int[] { 102, 39,
+ 39, 39, 39, 24 }));
this.setHardness(4.0F);
}
}
| true | true |
public BlockMiningMachine(IndustrialInc plugin) {
super(plugin, "Mining Machine", new DesignGenericBlock(plugin,
plugin.assets.getTexture("block_machine"), new int[] { 103, 40,
40, 40, 40, 24 }));
this.setHardness(4.0F);
}
|
public BlockMiningMachine(IndustrialInc plugin) {
super(plugin, "Mining Machine", new DesignGenericBlock(plugin,
plugin.assets.getTexture("block_machine"), new int[] { 102, 39,
39, 39, 39, 24 }));
this.setHardness(4.0F);
}
|
diff --git a/src/com/term/RandomChoise.java b/src/com/term/RandomChoise.java
index 21303b9..c42d549 100644
--- a/src/com/term/RandomChoise.java
+++ b/src/com/term/RandomChoise.java
@@ -1,71 +1,75 @@
package com.term;
import java.util.Random;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class RandomChoise extends Activity {
private static final String TAG = "RandomChoise";
Uri mUri;
Cursor mCursor;
int max = 0;
String random_result = "";
Random numx = new Random();
TextView tv;
Button buttonstart;
FoodProvider pro = new FoodProvider();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random_choise);
Intent intent = getIntent();
mUri = intent.getData();
tv = (TextView)findViewById(R.id.random_result);
buttonstart = (Button) findViewById(R.id.button_start);
buttonstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mCursor = managedQuery(mUri, FoodColumn.PROJECTION, null, null, null);
mCursor.moveToFirst();
max = mCursor.getCount();
- long id = numx.nextInt(max)+1;
- Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
- mCursor = managedQuery(uri, FoodColumn.PROJECTION, null, null, null);
- Log.e(TAG + ":onCreate", mCursor.toString() + " " + id + max);
+ long id = numx.nextInt(max);
+ while(id>0){
+ mCursor.moveToNext();
+ id=id-1;
+ }
+ //Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
+ //mCursor = managedQuery(uri, FoodColumn.PROJECTION, null, null, null);
+ //Log.e(TAG + ":onCreate", mCursor.toString() + " " + id + max);
//mCursor = pro.query(mUri, FoodColumn.PROJECTION, FoodColumn._ID, idnum, null);
- mCursor.moveToFirst();
+ //mCursor.moveToFirst();
random_result = mCursor.getString(FoodColumn.NAME_COLUMN);
tv.setText(random_result);
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
| false | true |
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random_choise);
Intent intent = getIntent();
mUri = intent.getData();
tv = (TextView)findViewById(R.id.random_result);
buttonstart = (Button) findViewById(R.id.button_start);
buttonstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mCursor = managedQuery(mUri, FoodColumn.PROJECTION, null, null, null);
mCursor.moveToFirst();
max = mCursor.getCount();
long id = numx.nextInt(max)+1;
Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
mCursor = managedQuery(uri, FoodColumn.PROJECTION, null, null, null);
Log.e(TAG + ":onCreate", mCursor.toString() + " " + id + max);
//mCursor = pro.query(mUri, FoodColumn.PROJECTION, FoodColumn._ID, idnum, null);
mCursor.moveToFirst();
random_result = mCursor.getString(FoodColumn.NAME_COLUMN);
tv.setText(random_result);
}
});
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random_choise);
Intent intent = getIntent();
mUri = intent.getData();
tv = (TextView)findViewById(R.id.random_result);
buttonstart = (Button) findViewById(R.id.button_start);
buttonstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mCursor = managedQuery(mUri, FoodColumn.PROJECTION, null, null, null);
mCursor.moveToFirst();
max = mCursor.getCount();
long id = numx.nextInt(max);
while(id>0){
mCursor.moveToNext();
id=id-1;
}
//Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
//mCursor = managedQuery(uri, FoodColumn.PROJECTION, null, null, null);
//Log.e(TAG + ":onCreate", mCursor.toString() + " " + id + max);
//mCursor = pro.query(mUri, FoodColumn.PROJECTION, FoodColumn._ID, idnum, null);
//mCursor.moveToFirst();
random_result = mCursor.getString(FoodColumn.NAME_COLUMN);
tv.setText(random_result);
}
});
}
|
diff --git a/src/test/java/org/nohope/logging/EnhancedLoggerTest.java b/src/test/java/org/nohope/logging/EnhancedLoggerTest.java
index 916db33..05b5e5a 100644
--- a/src/test/java/org/nohope/logging/EnhancedLoggerTest.java
+++ b/src/test/java/org/nohope/logging/EnhancedLoggerTest.java
@@ -1,39 +1,39 @@
package org.nohope.logging;
import org.easymock.Capture;
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
/**
* @author ketoth xupack <[email protected]>
* @since 3/19/12 11:19 PM
*/
public final class EnhancedLoggerTest {
@Test
public void debug() {
- org.slf4j.Logger logger = createMock(org.slf4j.Logger.class);
+ final org.slf4j.Logger logger = createMock(org.slf4j.Logger.class);
- Capture<Object[]> argsC = new Capture<Object[]>();
- Capture<String> formatC = new Capture<String>();
+ final Capture<Object[]> argsC = new Capture<>();
+ final Capture<String> formatC = new Capture<>();
logger.debug(capture(formatC), capture(argsC));
expectLastCall();
replay(logger);
- EnhancedLogger elogger = new EnhancedLogger(logger);
+ final EnhancedLogger elogger = new EnhancedLogger(logger);
elogger.debug("%s %s %s %s %s", 1, 2, 3, 4, 5);
assertEquals("%s %s %s %s %s", formatC.getValue());
verify(logger);
- Logger logger1 = LoggerFactory.getLogger(EnhancedLoggerTest.class);
+ final Logger logger1 = LoggerFactory.getLogger(EnhancedLoggerTest.class);
logger1.warn(new IllegalStateException(), "{} {}", 1, 2);
}
}
| false | true |
public void debug() {
org.slf4j.Logger logger = createMock(org.slf4j.Logger.class);
Capture<Object[]> argsC = new Capture<Object[]>();
Capture<String> formatC = new Capture<String>();
logger.debug(capture(formatC), capture(argsC));
expectLastCall();
replay(logger);
EnhancedLogger elogger = new EnhancedLogger(logger);
elogger.debug("%s %s %s %s %s", 1, 2, 3, 4, 5);
assertEquals("%s %s %s %s %s", formatC.getValue());
verify(logger);
Logger logger1 = LoggerFactory.getLogger(EnhancedLoggerTest.class);
logger1.warn(new IllegalStateException(), "{} {}", 1, 2);
}
|
public void debug() {
final org.slf4j.Logger logger = createMock(org.slf4j.Logger.class);
final Capture<Object[]> argsC = new Capture<>();
final Capture<String> formatC = new Capture<>();
logger.debug(capture(formatC), capture(argsC));
expectLastCall();
replay(logger);
final EnhancedLogger elogger = new EnhancedLogger(logger);
elogger.debug("%s %s %s %s %s", 1, 2, 3, 4, 5);
assertEquals("%s %s %s %s %s", formatC.getValue());
verify(logger);
final Logger logger1 = LoggerFactory.getLogger(EnhancedLoggerTest.class);
logger1.warn(new IllegalStateException(), "{} {}", 1, 2);
}
|
diff --git a/src/main/java/org/bukkit/command/defaults/TimingsCommand.java b/src/main/java/org/bukkit/command/defaults/TimingsCommand.java
index f4da879b..9e5b6769 100644
--- a/src/main/java/org/bukkit/command/defaults/TimingsCommand.java
+++ b/src/main/java/org/bukkit/command/defaults/TimingsCommand.java
@@ -1,94 +1,102 @@
package org.bukkit.command.defaults;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.plugin.TimedRegisteredListener;
public class TimingsCommand extends Command {
public TimingsCommand(String name) {
super(name);
this.description = "Records timings for all plugin events";
this.usageMessage = "/timings <reset|merged|separate>";
this.setPermission("bukkit.command.timings");
}
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
if (!sender.getServer().getPluginManager().useTimings()) {
sender.sendMessage("Please enable timings by setting \"settings.plugin-profiling\" to true in bukkit.yml");
return true;
}
boolean separate = "separate".equals(args[0]);
if ("reset".equals(args[0])) {
for (HandlerList handlerList : HandlerList.getHandlerLists()) {
for (RegisteredListener listener : handlerList.getRegisteredListeners()) {
if (listener instanceof TimedRegisteredListener) {
((TimedRegisteredListener)listener).reset();
}
}
}
sender.sendMessage("Timings reset");
} else if ("merged".equals(args[0]) || separate) {
int index = 0;
int pluginIdx = 0;
File timingFolder = new File("timings");
timingFolder.mkdirs();
File timings = new File(timingFolder, "timings.txt");
File names = null;
while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
+ PrintStream fileTimings = null;
+ PrintStream fileNames = null;
try {
- PrintStream fileTimings = new PrintStream(timings);
- PrintStream fileNames = null;
+ fileTimings = new PrintStream(timings);
if (separate) {
names = new File(timingFolder, "names" + index + ".txt");
fileNames = new PrintStream(names);
}
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
pluginIdx++;
long totalTime = 0;
if (separate) {
fileNames.println(pluginIdx + " " + plugin.getDescription().getFullName());
fileTimings.println("Plugin " + pluginIdx);
}
else fileTimings.println(plugin.getDescription().getFullName());
for (RegisteredListener listener : HandlerList.getRegisteredListeners(plugin)) {
if (listener instanceof TimedRegisteredListener) {
TimedRegisteredListener trl = (TimedRegisteredListener) listener;
long time = trl.getTotalTime();
int count = trl.getCount();
if (count == 0) continue;
long avg = time / count;
totalTime += time;
Event event = trl.getEvent();
if (count > 0 && event != null) {
fileTimings.println(" " + event.getClass().getSimpleName() + (trl.hasMultiple() ? " (and others)" : "") + " Time: " + time + " Count: " + count + " Avg: " + avg);
}
}
}
fileTimings.println(" Total time " + totalTime + " (" + totalTime / 1000000000 + "s)");
}
sender.sendMessage("Timings written to " + timings.getPath());
if (separate) sender.sendMessage("Names written to " + names.getPath());
} catch (IOException e) {
+ } finally {
+ if (fileTimings != null) {
+ fileTimings.close();
+ }
+ if (fileNames != null) {
+ fileNames.close();
+ }
}
}
return true;
}
}
| false | true |
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
if (!sender.getServer().getPluginManager().useTimings()) {
sender.sendMessage("Please enable timings by setting \"settings.plugin-profiling\" to true in bukkit.yml");
return true;
}
boolean separate = "separate".equals(args[0]);
if ("reset".equals(args[0])) {
for (HandlerList handlerList : HandlerList.getHandlerLists()) {
for (RegisteredListener listener : handlerList.getRegisteredListeners()) {
if (listener instanceof TimedRegisteredListener) {
((TimedRegisteredListener)listener).reset();
}
}
}
sender.sendMessage("Timings reset");
} else if ("merged".equals(args[0]) || separate) {
int index = 0;
int pluginIdx = 0;
File timingFolder = new File("timings");
timingFolder.mkdirs();
File timings = new File(timingFolder, "timings.txt");
File names = null;
while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
try {
PrintStream fileTimings = new PrintStream(timings);
PrintStream fileNames = null;
if (separate) {
names = new File(timingFolder, "names" + index + ".txt");
fileNames = new PrintStream(names);
}
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
pluginIdx++;
long totalTime = 0;
if (separate) {
fileNames.println(pluginIdx + " " + plugin.getDescription().getFullName());
fileTimings.println("Plugin " + pluginIdx);
}
else fileTimings.println(plugin.getDescription().getFullName());
for (RegisteredListener listener : HandlerList.getRegisteredListeners(plugin)) {
if (listener instanceof TimedRegisteredListener) {
TimedRegisteredListener trl = (TimedRegisteredListener) listener;
long time = trl.getTotalTime();
int count = trl.getCount();
if (count == 0) continue;
long avg = time / count;
totalTime += time;
Event event = trl.getEvent();
if (count > 0 && event != null) {
fileTimings.println(" " + event.getClass().getSimpleName() + (trl.hasMultiple() ? " (and others)" : "") + " Time: " + time + " Count: " + count + " Avg: " + avg);
}
}
}
fileTimings.println(" Total time " + totalTime + " (" + totalTime / 1000000000 + "s)");
}
sender.sendMessage("Timings written to " + timings.getPath());
if (separate) sender.sendMessage("Names written to " + names.getPath());
} catch (IOException e) {
}
}
return true;
}
|
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
if (!sender.getServer().getPluginManager().useTimings()) {
sender.sendMessage("Please enable timings by setting \"settings.plugin-profiling\" to true in bukkit.yml");
return true;
}
boolean separate = "separate".equals(args[0]);
if ("reset".equals(args[0])) {
for (HandlerList handlerList : HandlerList.getHandlerLists()) {
for (RegisteredListener listener : handlerList.getRegisteredListeners()) {
if (listener instanceof TimedRegisteredListener) {
((TimedRegisteredListener)listener).reset();
}
}
}
sender.sendMessage("Timings reset");
} else if ("merged".equals(args[0]) || separate) {
int index = 0;
int pluginIdx = 0;
File timingFolder = new File("timings");
timingFolder.mkdirs();
File timings = new File(timingFolder, "timings.txt");
File names = null;
while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
PrintStream fileTimings = null;
PrintStream fileNames = null;
try {
fileTimings = new PrintStream(timings);
if (separate) {
names = new File(timingFolder, "names" + index + ".txt");
fileNames = new PrintStream(names);
}
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
pluginIdx++;
long totalTime = 0;
if (separate) {
fileNames.println(pluginIdx + " " + plugin.getDescription().getFullName());
fileTimings.println("Plugin " + pluginIdx);
}
else fileTimings.println(plugin.getDescription().getFullName());
for (RegisteredListener listener : HandlerList.getRegisteredListeners(plugin)) {
if (listener instanceof TimedRegisteredListener) {
TimedRegisteredListener trl = (TimedRegisteredListener) listener;
long time = trl.getTotalTime();
int count = trl.getCount();
if (count == 0) continue;
long avg = time / count;
totalTime += time;
Event event = trl.getEvent();
if (count > 0 && event != null) {
fileTimings.println(" " + event.getClass().getSimpleName() + (trl.hasMultiple() ? " (and others)" : "") + " Time: " + time + " Count: " + count + " Avg: " + avg);
}
}
}
fileTimings.println(" Total time " + totalTime + " (" + totalTime / 1000000000 + "s)");
}
sender.sendMessage("Timings written to " + timings.getPath());
if (separate) sender.sendMessage("Names written to " + names.getPath());
} catch (IOException e) {
} finally {
if (fileTimings != null) {
fileTimings.close();
}
if (fileNames != null) {
fileNames.close();
}
}
}
return true;
}
|
diff --git a/code/LuaTable.java b/code/LuaTable.java
index 1cb98a6..98ece39 100644
--- a/code/LuaTable.java
+++ b/code/LuaTable.java
@@ -1,67 +1,67 @@
// $Header$
/**
* Class that models Lua's tables. Each Lua table is an instance of
* this class.
*/
public final class LuaTable extends java.util.Hashtable {
private Object metatable;
/**
* Getter for metatable member.
* @return The metatable.
*/
Object getMetatable() {
return metatable;
}
/**
* Setter for metatable member.
* @param metatable The metatable.
*/
// :todo: Support metatable's __gc and __mode keys appropriately.
// This involves detecting when those keys are present in the
// metatable, and changing all the entries in the Hashtable
// to be instance of java.lang.Ref as appropriate.
void setMetatable(Object metatable) {
this.metatable = metatable;
return;
}
/**
* Like put for numeric (integer) keys.
*/
void putnum(int k, Object v) {
put(new Double(k), v);
}
/**
* Supports Lua's length (#) operator. More or less equivalent to
* "unbound_search" in ltable.c.
*/
int getn() {
int i = 0;
int j = 1;
// Find 'i' and 'j' such that i is present and j is not.
while (get(new Double(j)) != null) {
i = j;
j *= 2;
if (j < 0) { // overflow
// Pathological case. Linear search.
i = 1;
while (get(new Double(i)) != null) {
++i;
}
return i-1;
}
}
// binary search between i and j
- while (j - 1 > 1) {
+ while (j - i > 1) {
int m = (i+j)/2;
- if (get(new Double(m)) != null) {
+ if (get(new Double(m)) == null) {
j = m;
} else {
i = m;
}
}
return i;
}
}
| false | true |
int getn() {
int i = 0;
int j = 1;
// Find 'i' and 'j' such that i is present and j is not.
while (get(new Double(j)) != null) {
i = j;
j *= 2;
if (j < 0) { // overflow
// Pathological case. Linear search.
i = 1;
while (get(new Double(i)) != null) {
++i;
}
return i-1;
}
}
// binary search between i and j
while (j - 1 > 1) {
int m = (i+j)/2;
if (get(new Double(m)) != null) {
j = m;
} else {
i = m;
}
}
return i;
}
|
int getn() {
int i = 0;
int j = 1;
// Find 'i' and 'j' such that i is present and j is not.
while (get(new Double(j)) != null) {
i = j;
j *= 2;
if (j < 0) { // overflow
// Pathological case. Linear search.
i = 1;
while (get(new Double(i)) != null) {
++i;
}
return i-1;
}
}
// binary search between i and j
while (j - i > 1) {
int m = (i+j)/2;
if (get(new Double(m)) == null) {
j = m;
} else {
i = m;
}
}
return i;
}
|
diff --git a/opal-shell/src/main/java/org/obiba/opal/shell/commands/CopyCommand.java b/opal-shell/src/main/java/org/obiba/opal/shell/commands/CopyCommand.java
index df6c94fd6..24ef967c5 100644
--- a/opal-shell/src/main/java/org/obiba/opal/shell/commands/CopyCommand.java
+++ b/opal-shell/src/main/java/org/obiba/opal/shell/commands/CopyCommand.java
@@ -1,232 +1,232 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.opal.shell.commands;
import java.util.HashMap;
import java.util.Set;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.obiba.magma.Datasource;
import org.obiba.magma.MagmaEngine;
import org.obiba.magma.NoSuchDatasourceException;
import org.obiba.magma.NoSuchValueTableException;
import org.obiba.magma.ValueTable;
import org.obiba.magma.datasource.excel.ExcelDatasource;
import org.obiba.magma.js.support.JavascriptMultiplexingStrategy;
import org.obiba.magma.js.support.JavascriptVariableTransformer;
import org.obiba.magma.support.DatasourceCopier;
import org.obiba.magma.support.MagmaEngineTableResolver;
import org.obiba.opal.core.service.ExportException;
import org.obiba.opal.core.service.ExportService;
import org.obiba.opal.shell.commands.options.CopyCommandOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.collect.ImmutableSet;
/**
* Provides ability to copy Magma tables to an existing datasource or an Excel file.
*/
@CommandUsage(description = "Copy tables to an existing destination datasource or to a specified Excel file. The tables can be explicitly named and/or be the ones from a specified source datasource. The variables can be optionally processed: dispatched in another table and/or renamed.", syntax = "Syntax: copy [--source NAME] (--destination NAME | --out FILE) [--multiplex SCRIPT] [--transform SCRIPT] [--nonIncremental] [--catalogue] [TABLE_NAME...]")
public class CopyCommand extends AbstractOpalRuntimeDependentCommand<CopyCommandOptions> {
@Autowired
private ExportService exportService;
private static final Logger log = LoggerFactory.getLogger(CopyCommand.class);
public void setExportService(ExportService exportService) {
this.exportService = exportService;
}
public void execute() {
if(options.getTables() != null && !options.isSource()) {
if(validateOptions()) {
Datasource destinationDatasource = null;
try {
destinationDatasource = getDestinationDatasource();
exportService.exportTablesToDatasource(getValueTables(), destinationDatasource, buildDatasourceCopier(destinationDatasource), !options.getNonIncremental());
} catch(ExportException e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} catch(Exception e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} finally {
if(options.isOut() && destinationDatasource != null) {
try {
MagmaEngine.get().removeDatasource(destinationDatasource);
} catch(RuntimeException e) {
}
}
}
}
} else {
- getShell().printf("%s\n", "Neither source not table name(s) are specified.");
+ getShell().printf("%s\n", "Neither source nor table name(s) are specified.");
}
}
private DatasourceCopier buildDatasourceCopier(Datasource destinationDatasource) {
// build a datasource copier according to options
DatasourceCopier.Builder builder;
if(options.getCatalogue()) {
builder = DatasourceCopier.Builder.newCopier().dontCopyValues();
} else {
// get a builder with logging facilities
builder = exportService.newCopier(destinationDatasource);
}
if(options.isMultiplex()) {
builder.withMultiplexingStrategy(new JavascriptMultiplexingStrategy(options.getMultiplex()));
}
if(options.isTransform()) {
builder.withVariableTransformer(new JavascriptVariableTransformer(options.getTransform()));
}
return builder.build();
}
private Datasource getDestinationDatasource() {
Datasource destinationDatasource;
if(options.isDestination()) {
destinationDatasource = getDatasourceByName(options.getDestination());
} else {
FileObject outputFile = getOuputFile();
destinationDatasource = new ExcelDatasource(outputFile.getName().getBaseName(), getLocalFile(outputFile));
MagmaEngine.get().addDatasource(destinationDatasource);
}
return destinationDatasource;
}
private Set<ValueTable> getValueTables() {
HashMap<String, ValueTable> names = new HashMap<String, ValueTable>();
if(options.isSource()) {
for(ValueTable table : getDatasourceByName(options.getSource()).getValueTables()) {
names.put(table.getDatasource().getName() + "." + table.getName(), table);
}
}
if(options.getTables() != null) {
for(String name : options.getTables()) {
if(!names.containsKey(name)) {
names.put(name, MagmaEngineTableResolver.valueOf(name).resolveTable());
}
}
}
return ImmutableSet.copyOf(names.values());
}
private Datasource getDatasourceByName(String datasourceName) {
return MagmaEngine.get().getDatasource(datasourceName);
}
private boolean validateOptions() {
boolean validated = validateDestination();
validated = validateSource(validated);
validated = validateTables(validated);
return validated;
}
private boolean validateTables(boolean validated) {
if(options.getTables() != null) {
for(String tableName : options.getTables()) {
MagmaEngineTableResolver resolver = MagmaEngineTableResolver.valueOf(tableName);
try {
resolver.resolveTable();
} catch(NoSuchDatasourceException e) {
getShell().printf("'%s' refers to an unknown datasource: '%s'.\n", tableName, resolver.getDatasourceName());
validated = false;
} catch(NoSuchValueTableException e) {
getShell().printf("Table '%s' does not exist in datasource : '%s'.\n", resolver.getTableName(), resolver.getDatasourceName());
validated = false;
}
}
}
return validated;
}
private boolean validateSource(boolean validated) {
if(options.isSource()) {
try {
getDatasourceByName(options.getSource());
} catch(NoSuchDatasourceException e) {
getShell().printf("Destination datasource '%s' does not exist.\n", options.getDestination());
validated = false;
}
}
return validated;
}
private boolean validateDestination() {
boolean validated = true;
if(!options.isDestination() && !options.isOut()) {
getShell().printf("Must provide either the 'destination' option or the 'out' option.\n");
validated = false;
}
if(options.isDestination() && options.isOut()) {
getShell().printf("The 'destination' option and the 'out' option are mutually exclusive.\n");
validated = false;
}
if(options.isDestination()) {
try {
getDatasourceByName(options.getDestination());
} catch(NoSuchDatasourceException e) {
getShell().printf("Destination datasource '%s' does not exist.\n", options.getDestination());
validated = false;
}
}
return validated;
}
/**
* Get the output file to which the metadata will be exported to.
*
* @return The output file.
* @throws FileSystemException
*/
private FileObject getOuputFile() {
try {
// Get the file specified on the command line.
return resolveOutputFileAndCreateParentFolders();
} catch(FileSystemException e) {
log.error("There was an error accessing the output file", e);
throw new RuntimeException("There was an error accessing the output file", e);
}
}
/**
* Resolves the output file based on the command parameter. Creates the necessary parent folders (when required).
*
* @return A FileObject representing the ouput file.
* @throws FileSystemException
*/
private FileObject resolveOutputFileAndCreateParentFolders() throws FileSystemException {
FileObject outputFile = getFileSystemRoot().resolveFile(options.getOut());
// Create the parent directory, if it doesn't already exist.
FileObject directory = outputFile.getParent();
if(directory != null) {
directory.createFolder();
}
if(outputFile.getName().getExtension().equals("xls")) {
getShell().printf("WARNING: Writing to an Excel 97 spreadsheet. These are limited to 256 columns and 65536 rows which may not be sufficient for writing large tables.\nUse an 'xlsx' extension to use Excel 2007 format which supports 16K columns.\n");
}
return outputFile;
}
}
| true | true |
public void execute() {
if(options.getTables() != null && !options.isSource()) {
if(validateOptions()) {
Datasource destinationDatasource = null;
try {
destinationDatasource = getDestinationDatasource();
exportService.exportTablesToDatasource(getValueTables(), destinationDatasource, buildDatasourceCopier(destinationDatasource), !options.getNonIncremental());
} catch(ExportException e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} catch(Exception e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} finally {
if(options.isOut() && destinationDatasource != null) {
try {
MagmaEngine.get().removeDatasource(destinationDatasource);
} catch(RuntimeException e) {
}
}
}
}
} else {
getShell().printf("%s\n", "Neither source not table name(s) are specified.");
}
}
|
public void execute() {
if(options.getTables() != null && !options.isSource()) {
if(validateOptions()) {
Datasource destinationDatasource = null;
try {
destinationDatasource = getDestinationDatasource();
exportService.exportTablesToDatasource(getValueTables(), destinationDatasource, buildDatasourceCopier(destinationDatasource), !options.getNonIncremental());
} catch(ExportException e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} catch(Exception e) {
getShell().printf("%s\n", e.getMessage());
e.printStackTrace(System.err);
} finally {
if(options.isOut() && destinationDatasource != null) {
try {
MagmaEngine.get().removeDatasource(destinationDatasource);
} catch(RuntimeException e) {
}
}
}
}
} else {
getShell().printf("%s\n", "Neither source nor table name(s) are specified.");
}
}
|
diff --git a/src/main/java/org/iplantc/de/server/ConfluenceProperties.java b/src/main/java/org/iplantc/de/server/ConfluenceProperties.java
index 6ee90dd..bf47b4f 100644
--- a/src/main/java/org/iplantc/de/server/ConfluenceProperties.java
+++ b/src/main/java/org/iplantc/de/server/ConfluenceProperties.java
@@ -1,152 +1,151 @@
package org.iplantc.de.server;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* Contains methods for accessing the confluence.properties file.
*
* @author hariolf
*
*/
public class ConfluenceProperties {
private final Logger LOGGER = Logger.getLogger(ConfluenceProperties.class);
// The prefix for all of the properties.
private static final String PREFIX = "org.iplantc.discoveryenvironment.confluence"; //$NON-NLS-1$
private static final String CONFLUENCE_BASE_URL = PREFIX + ".baseUrl"; //$NON-NLS-1$
private static final String CONFLUENCE_PARENT_PAGE = PREFIX + ".parentPageName"; //$NON-NLS-1$
private static final String CONFLUENCE_USER = PREFIX + ".user"; //$NON-NLS-1$
private static final String CONFLUENCE_PASSWORD = PREFIX + ".password"; //$NON-NLS-1$
private static final String CONFLUENCE_SPACE_NAME = PREFIX + ".spaceName"; //$NON-NLS-1$
private static final String CONFLUENCE_SPACE_URL = PREFIX + ".spaceUrl"; //$NON-NLS-1$
/** this is an internationalized string #translate #i18n */
private static final String CONFLUENCE_COMMENT_SUFFIX = PREFIX + ".ratingCommentSuffix"; //$NON-NLS-1$
private Properties properties;
/**
* The list of required properties.
*/
private final static String[] REQUIRED_PROPERTIES = {CONFLUENCE_BASE_URL, CONFLUENCE_PARENT_PAGE,
CONFLUENCE_USER, CONFLUENCE_PASSWORD, CONFLUENCE_SPACE_NAME, CONFLUENCE_SPACE_URL,
CONFLUENCE_COMMENT_SUFFIX};
/**
* Creates a new ConfluenceProperties object and loads properties.
*
* @param propFileName the name of the properties file
*/
public ConfluenceProperties(String propFileName) {
loadProperties(propFileName);
validateProperties(REQUIRED_PROPERTIES);
}
/**
* Validates that we have values for all required properties.
*
* @throws RuntimeException if a required property isn't found in the file
*/
private void validateProperties(String[] propertyNames) {
for (String propertyName : propertyNames) {
String propertyValue = properties.getProperty(propertyName);
if (propertyValue == null || propertyValue.equals("")) { //$NON-NLS-1$
throw new RuntimeException("missing required property: " + propertyName); //$NON-NLS-1$
}
}
}
/**
* Loads the discovery environment properties. If an error occurs while loading the file, we log the
* message, but do not throw an exception; the property validation will catch any required properties
* that are missing.
*
* @param propFileName the name of the properties file
*/
private void loadProperties(String propFileName) {
properties = new Properties();
InputStream stream = ConfluenceProperties.class.getResourceAsStream(propFileName);
try {
properties.load(stream);
} catch (IOException e) {
String msg = "unable to load discovery environment properties"; //$NON-NLS-1$
LOGGER.error(msg, e);
- }
- finally { // FIXME eclipse auto indent fail
+ } finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Cannot close input stream for file " + propFileName, e); //$NON-NLS-1$
- }
- }
+ }
+ }
}
}
/**
* Gets the base URL used to access the Confluence wiki.
*
* @return the URL as a string.
*/
public String getConfluenceBaseUrl() {
return properties.getProperty(CONFLUENCE_BASE_URL);
}
/**
* Gets the name of the 'List of Applications' page.
*
* @return the name as a string.
*/
public String getConfluenceParentPage() {
return properties.getProperty(CONFLUENCE_PARENT_PAGE);
}
/**
* Gets the Confluence user for adding documentation pages.
*
* @return the user name
*/
public String getConfluenceUser() {
return properties.getProperty(CONFLUENCE_USER);
}
/**
* Gets the Confluence password for adding documentation pages.
*
* @return the password
*/
public String getConfluencePassword() {
return properties.getProperty(CONFLUENCE_PASSWORD);
}
/**
* Gets the name of the 'DE Applications' space in Confluence.
*
* @return the name as a string.
*/
public String getConfluenceSpaceName() {
return properties.getProperty(CONFLUENCE_SPACE_NAME);
}
/**
* Gets the URL of the 'DE Applications' space in Confluence.
*
* @return the URL as a string.
*/
public String getConfluenceSpaceUrl() {
return properties.getProperty(CONFLUENCE_SPACE_URL);
}
/**
* Gets localized text that is added to rating comments for the wiki; contains a placeholder for the
* current DE user.
*
* @return a string representing the localized text.
*/
public String getRatingCommentSuffix() {
return properties.getProperty(CONFLUENCE_COMMENT_SUFFIX);
}
}
| false | true |
private void loadProperties(String propFileName) {
properties = new Properties();
InputStream stream = ConfluenceProperties.class.getResourceAsStream(propFileName);
try {
properties.load(stream);
} catch (IOException e) {
String msg = "unable to load discovery environment properties"; //$NON-NLS-1$
LOGGER.error(msg, e);
}
finally { // FIXME eclipse auto indent fail
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Cannot close input stream for file " + propFileName, e); //$NON-NLS-1$
}
}
}
}
|
private void loadProperties(String propFileName) {
properties = new Properties();
InputStream stream = ConfluenceProperties.class.getResourceAsStream(propFileName);
try {
properties.load(stream);
} catch (IOException e) {
String msg = "unable to load discovery environment properties"; //$NON-NLS-1$
LOGGER.error(msg, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Cannot close input stream for file " + propFileName, e); //$NON-NLS-1$
}
}
}
}
|
diff --git a/java/Bench.java b/java/Bench.java
index 4123e1e..0384d94 100644
--- a/java/Bench.java
+++ b/java/Bench.java
@@ -1,140 +1,140 @@
import java.util.Random;
import java.util.Arrays;
import java.util.ArrayList;
public class Bench {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("java Bench SORT_CLASS_NAME");
System.exit(1);
return;
}
Random random = new Random(0);
Data orig = new Data(random, 150000, 1000);
for (String name: args) {
bench(name, orig.copy(), true);
bench(name, orig.copy(), false);
}
}
static void bench(String name, Data data, boolean warmup)
throws Exception {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class<? extends Sort> sortClass =
classLoader.loadClass(name).asSubclass(Sort.class);
Sort sortObj = sortClass.newInstance();
long start;
long end;
start = System.currentTimeMillis();
sortObj.sort(data.natRandom);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] natRandom " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] natRandom " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.natAsc);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] natAsc " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] natAsc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.natDesc);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] natDesc " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] natDesc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objRandom, data.relation);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] objRandom " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] objRandom " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objAsc, data.relation);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] objAsc " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] objAsc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objDesc, data.relation);
end = System.currentTimeMillis();
- if (!warmup) puts("[" + name + "] objDesc " + (end - start) + "ns");
+ if (!warmup) puts("[" + name + "] objDesc " + (end - start) + "ms");
}
static class Data {
Data() {
}
Data(Random random, int size, int range) {
relation = new EntryRelation();
natRandom = new Integer[size];
natAsc = new Integer[size];
natDesc = new Integer[size];
objRandom = new Entry[size];
objAsc = new Entry[size];
objDesc = new Entry[size];
double rate = ((double) range) / size;
int value;
for (int i = 0; i < size; i++) {
value = random.nextInt(range);
natRandom[i] = value;
objRandom[i] = new Entry(value, i);
}
value = 0;
for (int i = 0; i < size; i++) {
if (random.nextDouble() > rate) value++;
natAsc[i] = value;
objAsc[i] = new Entry(value, i);
}
value = size;
for (int i = 0; i < size; i++) {
if (random.nextDouble() > rate) value--;
natDesc[i] = value;
objDesc[i] = new Entry(value, i);
}
}
Data copy() {
Data data = new Data();
data.relation = relation;
data.natRandom = Arrays.copyOf(natRandom, natRandom.length);
data.natAsc = Arrays.copyOf(natAsc, natAsc.length);
data.natDesc = Arrays.copyOf(natDesc, natDesc.length);
data.objRandom = Arrays.copyOf(objRandom, objRandom.length);
data.objAsc = Arrays.copyOf(objAsc, objAsc.length);
data.objDesc = Arrays.copyOf(objDesc, objDesc.length);
return data;
}
EntryRelation relation;
Integer[] natRandom;
Integer[] natAsc;
Integer[] natDesc;
Entry[] objRandom;
Entry[] objAsc;
Entry[] objDesc;
}
static class Entry {
int value;
int index;
public Entry(int value, int index) {
this.index = index;
this.value = value;
}
@Override public String toString() {
return "{value: " + value + ", index: " + index + "}";
}
}
static class EntryRelation extends Sort.Relation<Entry> {
@Override public boolean lessThan(Entry a, Entry b) {
return a.value < b.value;
}
}
private static void puts(String s) {
System.out.println(s);
}
}
| false | true |
static void bench(String name, Data data, boolean warmup)
throws Exception {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class<? extends Sort> sortClass =
classLoader.loadClass(name).asSubclass(Sort.class);
Sort sortObj = sortClass.newInstance();
long start;
long end;
start = System.currentTimeMillis();
sortObj.sort(data.natRandom);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natRandom " + (end - start) + "ns");
start = System.currentTimeMillis();
sortObj.sort(data.natAsc);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natAsc " + (end - start) + "ns");
start = System.currentTimeMillis();
sortObj.sort(data.natDesc);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natDesc " + (end - start) + "ns");
start = System.currentTimeMillis();
sortObj.sort(data.objRandom, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objRandom " + (end - start) + "ns");
start = System.currentTimeMillis();
sortObj.sort(data.objAsc, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objAsc " + (end - start) + "ns");
start = System.currentTimeMillis();
sortObj.sort(data.objDesc, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objDesc " + (end - start) + "ns");
}
|
static void bench(String name, Data data, boolean warmup)
throws Exception {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class<? extends Sort> sortClass =
classLoader.loadClass(name).asSubclass(Sort.class);
Sort sortObj = sortClass.newInstance();
long start;
long end;
start = System.currentTimeMillis();
sortObj.sort(data.natRandom);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natRandom " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.natAsc);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natAsc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.natDesc);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] natDesc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objRandom, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objRandom " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objAsc, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objAsc " + (end - start) + "ms");
start = System.currentTimeMillis();
sortObj.sort(data.objDesc, data.relation);
end = System.currentTimeMillis();
if (!warmup) puts("[" + name + "] objDesc " + (end - start) + "ms");
}
|
diff --git a/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java b/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
index ae40393..b39da8d 100644
--- a/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
+++ b/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
@@ -1,58 +1,61 @@
package com.openfeint.qa.core.caze.step.definition;
import android.util.Log;
import java.util.Hashtable;
import java.util.Observable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import junit.framework.AssertionFailedError;
public abstract class BasicStepDefinition extends Observable {
protected static Hashtable<String, Object> blockRepo = null;
private final Semaphore inStepSync = new Semaphore(0, true);
protected int TIMEOUT = 5000;
protected static Hashtable<String, Object> getBlockRepo() {
if (null == blockRepo) {
blockRepo = new Hashtable<String, Object>();
}
return blockRepo;
}
protected void setTimeout(int timeout) {
TIMEOUT = timeout;
}
/**
* notifys automation framework that current step is finished
*/
protected void notifyStepPass() {
setChanged();
notifyObservers("update waiting");
}
/**
* keeps waiting until a notifyAsync() call invoked
*
* @throws InterruptedException
*/
protected void waitForAsyncInStep() {
try {
- inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
+ boolean t = inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
+ if (!t) {
+ throw new AssertionFailedError();
+ }
+ } catch (InterruptedException e) {
throw new AssertionFailedError();
}
}
/**
* notifys async semaphore that current async call is finished
*/
protected void notifyAsyncInStep() {
inStepSync.release(1);
}
}
| true | true |
protected void waitForAsyncInStep() {
try {
inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new AssertionFailedError();
}
}
|
protected void waitForAsyncInStep() {
try {
boolean t = inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
if (!t) {
throw new AssertionFailedError();
}
} catch (InterruptedException e) {
throw new AssertionFailedError();
}
}
|
diff --git a/src/main/java/com/succinctllc/hazelcast/work/executor/DistributedExecutorService.java b/src/main/java/com/succinctllc/hazelcast/work/executor/DistributedExecutorService.java
index 5a92319..be0cf17 100644
--- a/src/main/java/com/succinctllc/hazelcast/work/executor/DistributedExecutorService.java
+++ b/src/main/java/com/succinctllc/hazelcast/work/executor/DistributedExecutorService.java
@@ -1,430 +1,435 @@
package com.succinctllc.hazelcast.work.executor;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import com.hazelcast.core.DistributedTask;
import com.hazelcast.core.Member;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.core.MultiTask;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.succinctllc.core.concurrent.BackoffTimer;
import com.succinctllc.core.concurrent.collections.grouped.Groupable;
import com.succinctllc.core.concurrent.collections.router.ListRouter;
import com.succinctllc.core.concurrent.collections.router.RoundRobinRouter;
import com.succinctllc.core.metrics.MetricNamer;
import com.succinctllc.hazelcast.work.HazelcastWork;
import com.succinctllc.hazelcast.work.HazelcastWorkManager;
import com.succinctllc.hazelcast.work.HazelcastWorkTopology;
import com.succinctllc.hazelcast.work.WorkId;
import com.succinctllc.hazelcast.work.WorkIdAdapter;
import com.succinctllc.hazelcast.work.executor.DistributedExecutorServiceBuilder.InternalBuilderStep2;
import com.succinctllc.hazelcast.work.metrics.LocalFuturesWaitingGauge;
import com.succinctllc.hazelcast.work.metrics.LocalIMapSizeGauge;
import com.succinctllc.hazelcast.work.metrics.PercentDuplicateRateGuage;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.TimerContext;
/**
* This is basically a proxy for executor service that returns nicely generic futures
* it wraps the work in another callable. It puts it into the HC map for writeAheadLog
* it sends a message of the work to other nodes
*
* TODO: a lot... most methods throw a not implemented exception
*
* TODO: add functionality to do further load balancing by adding more members into the
* ready member list and shuffling the list for example. Or another type of router that
* is aware of how backed up members are.
*
* TODO: implement work stealing. Because we push work to members, it is possible for
* one member to go slower than the others. In which case we should do 2 things:
* 1) allocate less work to this member and 2) allow other members to steal work from
* it if they don't have much to do.
*
* @author jclawson
*
*/
public class DistributedExecutorService implements ExecutorService {
private static ConcurrentMap<String, DistributedExecutorService> servicesByTopology = new ConcurrentHashMap<String, DistributedExecutorService>();
public static DistributedExecutorService get(String topology) {
return (DistributedExecutorService) servicesByTopology.get(topology);
}
private static ILogger LOGGER = Logger.getLogger(DistributedExecutorService.class.getName());
//private DistributedExecutorServiceManager distributedExecutorServiceManager;
private volatile boolean isReady = false;
private final ListRouter<Member> memberRouter;
private final WorkIdAdapter partitionAdapter;
private final LocalWorkExecutorService localExecutorService;
private final HazelcastWorkTopology topology;
private final ExecutorService workDistributor;
private final DistributedFutureTracker futureTracker;
private final boolean acknowledgeWorkSubmittion;
private final boolean disableWorkers;
private final MetricNamer metricNamer;
private final boolean statisticsEnabled;
private final MetricsRegistry metrics;
private com.yammer.metrics.core.Timer workAddedTimer;
private Meter worksAdded;
//max number of times to try and submit a work before giving up
private final int MAX_SUBMIT_TRIES = 10;
public static interface RunnablePartitionable extends Runnable, Groupable {
}
protected DistributedExecutorService(InternalBuilderStep2<?> internalBuilderStep1){
this.topology = internalBuilderStep1.topology;
this.partitionAdapter = internalBuilderStep1.partitionAdapter;
this.acknowledgeWorkSubmittion = internalBuilderStep1.acknowlegeWorkSubmission;
this.disableWorkers = internalBuilderStep1.disableWorkers;
this.metricNamer = internalBuilderStep1.metricNamer;
this.statisticsEnabled = internalBuilderStep1.metricsRegistry != null;
this.metrics = internalBuilderStep1.metricsRegistry;
workDistributor = topology.getWorkDistributor();
if (servicesByTopology.putIfAbsent(topology.getName(), this) != null) {
throw new IllegalArgumentException(
"A DistributedExecutorService already exists for the topology "
+ topology.getName());
}
this.localExecutorService = new LocalWorkExecutorService(topology, internalBuilderStep1.threadCount, metrics, metricNamer);
memberRouter = new RoundRobinRouter<Member>(new Callable<List<Member>>() {
public List<Member> call() throws Exception {
return topology.getReadyMembers();
}
});
futureTracker = new DistributedFutureTracker(this);
//TODO: move stats tracking to separate generic class
if(statisticsEnabled) {
workAddedTimer = metrics.newTimer(createName("[submit] Call timer"), TimeUnit.MILLISECONDS, TimeUnit.MINUTES);
worksAdded = metrics.newMeter(createName("[submit] Work submitted"), "work added", TimeUnit.MINUTES);
metrics.newGauge(createName("[submit] Percent duplicate rate"), new PercentDuplicateRateGuage(worksAdded, workAddedTimer));
metrics.newGauge(createName("Pending futures count"), new LocalFuturesWaitingGauge(futureTracker));
metrics.newGauge(createName("Pending work map size (local)"), new LocalIMapSizeGauge(topology.getPendingWork()));
}
}
private MetricName createName(String name) {
return metricNamer.createMetricName(
"executor",
topology.getName(),
"DistributedExecutorService",
name
);
}
public void startup() {
if(!disableWorkers) {
localExecutorService.start();
isReady = true;
topology.localExecutorServiceReady();
}
//flush items that got left behind in the local map
//this must always be started on every single node!
//new Timer(topology.createName("flush-timer"), true)
// .schedule(new StaleWorkFlushTimerTask(this), 6000, 6000);
//using the backoff timer instead from 1 second - 30 seconds
//typical usage patterns will note that it will recover more items
//after the first execution so a backoff makes sense
BackoffTimer timer = new BackoffTimer(topology.createName("flush-timer"));
timer.schedule(new StaleWorkFlushTimerTask(this), 1000, 30000, 2);
timer.start();
}
public HazelcastWorkTopology getTopology(){
return this.topology;
}
public LocalWorkExecutorService getLocalExecutorService() {
return localExecutorService;
}
public boolean isReady() {
return isReady;
}
public void execute(Runnable command) {
execute(command, false);
}
protected void execute(Runnable command, boolean isResubmitting) {
doExecute(createHazelcastWorkWrapper(command), isResubmitting);
}
private HazelcastWork createHazelcastWorkWrapper(Runnable task){
if(task instanceof HazelcastWork) {
((HazelcastWork) task).updateCreatedTime();
return (HazelcastWork) task;
} else {
return new HazelcastWork(topology.getName(), partitionAdapter.createWorkId(task), task);
}
}
private HazelcastWork createHazelcastWorkWrapper(Callable<?> task){
if(task instanceof HazelcastWork) {
((HazelcastWork) task).updateCreatedTime();
return (HazelcastWork) task;
} else {
return new HazelcastWork(topology.getName(), partitionAdapter.createWorkId(task), task);
}
}
//TODO: make HazelcastWork package protected, detect if we are resubmitting if command instanceof HazelcastWork
protected void doExecute(HazelcastWork wrapper, boolean isResubmitting) {
TimerContext ctx = null;
if(statisticsEnabled) {
ctx = workAddedTimer.time();
}
try {
WorkId workKey = wrapper.getWorkId();
boolean executeTask = true;
/*
* with acknowledgeWorkSubmition, we will sit in this loop until a
* node accepts our work item. Currently, a node will accept as long as
* a MemberLeftException is not thrown
*/
int tries = 0;
while(++tries <= MAX_SUBMIT_TRIES) {
if(isResubmitting) {
wrapper.setSubmissionCount(wrapper.getSubmissionCount()+1);
topology.getPendingWork().put(workKey.getId(), wrapper);
} else {
executeTask = topology.getPendingWork().putIfAbsent(workKey.getId(), wrapper) == null;
}
if(executeTask) {
Member m = memberRouter.next();
if(m == null) {
LOGGER.log(Level.WARNING, "Work submitted to writeAheadLog but no members are online to do the work.");
return;
}
DistributedTask<Boolean> task = new DistributedTask<Boolean>(new SubmitWorkTask(wrapper, topology.getName()), m);
workDistributor.execute(task);
if(this.acknowledgeWorkSubmittion) {
try {
if(task.get()) {
if(worksAdded != null)
worksAdded.mark();
return;
} else {
+ LOGGER.log(Level.INFO, "The member "+m+" did not accept the work. Trying to resubmit to another node");
isResubmitting = true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.log(Level.WARNING, "Thread was interrupted waiting for work to be submitted", e);
return;
} catch (MemberLeftException e) {
//resubmit the work to another node
+ LOGGER.log(Level.WARNING, "Member left, trying to resubmit work to another node");
isResubmitting = true;
} catch (ExecutionException e) {
//TODO: improve this - we may need to retry here... for example if a node indicated it doesn't want to do the work
throw new RuntimeException("An error ocurred while distributing work", e);
}
} else {
if(worksAdded != null)
worksAdded.mark();
return;
}
+ } else {
+ LOGGER.log(Level.FINE, workKey.getId()+" is already in the system to be worked on. I will not resubmit it");
+ return;
}
}
if(tries > MAX_SUBMIT_TRIES) {
throw new RuntimeException("Unable to submit work to nodes. I tried "+MAX_SUBMIT_TRIES+" times.");
}
} finally {
if(ctx != null)
ctx.stop();
}
}
public <T> Future<T> submit(Callable<T> task) {
HazelcastWork work = createHazelcastWorkWrapper(task);
DistributedFuture<T> future = new DistributedFuture<T>();
futureTracker.add(work.getUniqueIdentifier(), future);
doExecute(work, false);
return future;
}
public void shutdown() {
MultiTask<List<Runnable>> task = new MultiTask<List<Runnable>>(
new ShutdownEvent(topology.getName(),
ShutdownEvent.ShutdownType.WAIT_AND_SHUTDOWN
),
topology.getHazelcast().getCluster().getMembers());
topology.getHazelcast().getExecutorService().execute(task);
}
public List<Runnable> shutdownNow() {
MultiTask<List<Runnable>> task = new MultiTask<List<Runnable>>(
new ShutdownEvent(topology.getName(),
ShutdownEvent.ShutdownType.SHUTDOWN_NOW
),
topology.getHazelcast().getCluster().getMembers());
topology.getHazelcast().getExecutorService().execute(task);
try {
LinkedList<Runnable> allRunnables = new LinkedList<Runnable>();
for(List<Runnable> list : task.get()) {
allRunnables.addAll(list);
}
return allRunnables;
} catch (ExecutionException e) {
throw new RuntimeException("Execution exception while shutting down the executor services", e);
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted while shutting down the executor services", e);
}
}
public Future<?> submit(Runnable task) {
HazelcastWork work = createHazelcastWorkWrapper(task);
DistributedFuture future = new DistributedFuture();
futureTracker.add(work.getUniqueIdentifier(), future);
doExecute(work, false);
return future;
}
public <T> Future<T> submit(Runnable task, T result) {
//TODO: make sure this task is hazelcast serializable
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public boolean isShutdown() {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public boolean isTerminated() {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public <T> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
// FIXME Implement this method
throw new RuntimeException("Not Implemented Yet");
}
protected MetricNamer getMetricNamer() {
return metricNamer;
}
protected boolean isStatisticsEnabled() {
return statisticsEnabled;
}
protected MetricsRegistry getMetrics() {
return metrics;
}
public DistributedFutureTracker getFutureTracker() {
return futureTracker;
}
private static class ShutdownEvent implements Callable<List<Runnable>>, Serializable {
private static final long serialVersionUID = 1L;
private static enum ShutdownType {
WAIT_AND_SHUTDOWN,
SHUTDOWN_NOW
}
private final ShutdownType type;
private String topology;
private ShutdownEvent(String topology, ShutdownType type){
this.type = type;
this.topology = topology;
}
public List<Runnable> call() throws Exception {
DistributedExecutorService dsvc = HazelcastWorkManager
.getDistributedExecutorService(topology);
if(dsvc == null) return Collections.emptyList();
LocalWorkExecutorService svc = dsvc.getLocalExecutorService();
if(svc == null) return Collections.emptyList();
switch(this.type) {
case SHUTDOWN_NOW:
return svc.shutdownNow();
case WAIT_AND_SHUTDOWN:
default:
svc.shutdown();
}
return null;
}
}
}
| false | true |
protected void doExecute(HazelcastWork wrapper, boolean isResubmitting) {
TimerContext ctx = null;
if(statisticsEnabled) {
ctx = workAddedTimer.time();
}
try {
WorkId workKey = wrapper.getWorkId();
boolean executeTask = true;
/*
* with acknowledgeWorkSubmition, we will sit in this loop until a
* node accepts our work item. Currently, a node will accept as long as
* a MemberLeftException is not thrown
*/
int tries = 0;
while(++tries <= MAX_SUBMIT_TRIES) {
if(isResubmitting) {
wrapper.setSubmissionCount(wrapper.getSubmissionCount()+1);
topology.getPendingWork().put(workKey.getId(), wrapper);
} else {
executeTask = topology.getPendingWork().putIfAbsent(workKey.getId(), wrapper) == null;
}
if(executeTask) {
Member m = memberRouter.next();
if(m == null) {
LOGGER.log(Level.WARNING, "Work submitted to writeAheadLog but no members are online to do the work.");
return;
}
DistributedTask<Boolean> task = new DistributedTask<Boolean>(new SubmitWorkTask(wrapper, topology.getName()), m);
workDistributor.execute(task);
if(this.acknowledgeWorkSubmittion) {
try {
if(task.get()) {
if(worksAdded != null)
worksAdded.mark();
return;
} else {
isResubmitting = true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.log(Level.WARNING, "Thread was interrupted waiting for work to be submitted", e);
return;
} catch (MemberLeftException e) {
//resubmit the work to another node
isResubmitting = true;
} catch (ExecutionException e) {
//TODO: improve this - we may need to retry here... for example if a node indicated it doesn't want to do the work
throw new RuntimeException("An error ocurred while distributing work", e);
}
} else {
if(worksAdded != null)
worksAdded.mark();
return;
}
}
}
if(tries > MAX_SUBMIT_TRIES) {
throw new RuntimeException("Unable to submit work to nodes. I tried "+MAX_SUBMIT_TRIES+" times.");
}
} finally {
if(ctx != null)
ctx.stop();
}
}
|
protected void doExecute(HazelcastWork wrapper, boolean isResubmitting) {
TimerContext ctx = null;
if(statisticsEnabled) {
ctx = workAddedTimer.time();
}
try {
WorkId workKey = wrapper.getWorkId();
boolean executeTask = true;
/*
* with acknowledgeWorkSubmition, we will sit in this loop until a
* node accepts our work item. Currently, a node will accept as long as
* a MemberLeftException is not thrown
*/
int tries = 0;
while(++tries <= MAX_SUBMIT_TRIES) {
if(isResubmitting) {
wrapper.setSubmissionCount(wrapper.getSubmissionCount()+1);
topology.getPendingWork().put(workKey.getId(), wrapper);
} else {
executeTask = topology.getPendingWork().putIfAbsent(workKey.getId(), wrapper) == null;
}
if(executeTask) {
Member m = memberRouter.next();
if(m == null) {
LOGGER.log(Level.WARNING, "Work submitted to writeAheadLog but no members are online to do the work.");
return;
}
DistributedTask<Boolean> task = new DistributedTask<Boolean>(new SubmitWorkTask(wrapper, topology.getName()), m);
workDistributor.execute(task);
if(this.acknowledgeWorkSubmittion) {
try {
if(task.get()) {
if(worksAdded != null)
worksAdded.mark();
return;
} else {
LOGGER.log(Level.INFO, "The member "+m+" did not accept the work. Trying to resubmit to another node");
isResubmitting = true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.log(Level.WARNING, "Thread was interrupted waiting for work to be submitted", e);
return;
} catch (MemberLeftException e) {
//resubmit the work to another node
LOGGER.log(Level.WARNING, "Member left, trying to resubmit work to another node");
isResubmitting = true;
} catch (ExecutionException e) {
//TODO: improve this - we may need to retry here... for example if a node indicated it doesn't want to do the work
throw new RuntimeException("An error ocurred while distributing work", e);
}
} else {
if(worksAdded != null)
worksAdded.mark();
return;
}
} else {
LOGGER.log(Level.FINE, workKey.getId()+" is already in the system to be worked on. I will not resubmit it");
return;
}
}
if(tries > MAX_SUBMIT_TRIES) {
throw new RuntimeException("Unable to submit work to nodes. I tried "+MAX_SUBMIT_TRIES+" times.");
}
} finally {
if(ctx != null)
ctx.stop();
}
}
|
diff --git a/src/com/ryanmichela/MCStats2/controller/StatsEntityListener.java b/src/com/ryanmichela/MCStats2/controller/StatsEntityListener.java
index 31891ae..cc5e53c 100644
--- a/src/com/ryanmichela/MCStats2/controller/StatsEntityListener.java
+++ b/src/com/ryanmichela/MCStats2/controller/StatsEntityListener.java
@@ -1,57 +1,57 @@
package com.ryanmichela.MCStats2.controller;
//Copyright (C) 2010 Ryan Michela
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
public class StatsEntityListener extends EntityListener {
private StatsController controller;
public StatsEntityListener(StatsController controller) {
this.controller = controller;
}
@Override
public void onEntityDeath(EntityDeathEvent event) {
if(event.getEntity() instanceof Player) {
controller.die((Player)event.getEntity());
}
}
@Override
public void onEntityDamage(EntityDamageEvent event) {
if(!event.isCancelled()) {
if(event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent hostileEvent = (EntityDamageByEntityEvent) event;
if(hostileEvent.getEntity() instanceof LivingEntity && hostileEvent.getDamager() instanceof Player) {
Player damager = (Player)hostileEvent.getDamager();
LivingEntity damagee = (LivingEntity)hostileEvent.getEntity();
- if(damagee.getHealth() - event.getDamage() <= 0) {
+ if(damagee.getHealth() > 0 && damagee.getHealth() - event.getDamage() <= 0) {
controller.kill(damager, damagee);
}
}
}
}
}
}
| true | true |
public void onEntityDamage(EntityDamageEvent event) {
if(!event.isCancelled()) {
if(event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent hostileEvent = (EntityDamageByEntityEvent) event;
if(hostileEvent.getEntity() instanceof LivingEntity && hostileEvent.getDamager() instanceof Player) {
Player damager = (Player)hostileEvent.getDamager();
LivingEntity damagee = (LivingEntity)hostileEvent.getEntity();
if(damagee.getHealth() - event.getDamage() <= 0) {
controller.kill(damager, damagee);
}
}
}
}
}
|
public void onEntityDamage(EntityDamageEvent event) {
if(!event.isCancelled()) {
if(event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent hostileEvent = (EntityDamageByEntityEvent) event;
if(hostileEvent.getEntity() instanceof LivingEntity && hostileEvent.getDamager() instanceof Player) {
Player damager = (Player)hostileEvent.getDamager();
LivingEntity damagee = (LivingEntity)hostileEvent.getEntity();
if(damagee.getHealth() > 0 && damagee.getHealth() - event.getDamage() <= 0) {
controller.kill(damager, damagee);
}
}
}
}
}
|
diff --git a/drools-core/src/main/java/org/drools/io/impl/UrlResource.java b/drools-core/src/main/java/org/drools/io/impl/UrlResource.java
index 274462b1dd..61823f20f8 100644
--- a/drools-core/src/main/java/org/drools/io/impl/UrlResource.java
+++ b/drools-core/src/main/java/org/drools/io/impl/UrlResource.java
@@ -1,367 +1,367 @@
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.io.impl;
import java.io.Externalizable;
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.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.drools.core.util.StringUtils;
import org.drools.io.internal.InternalResource;
import org.drools.util.codec.Base64;
import org.kie.io.Resource;
import org.kie.io.ResourceType;
/**
* Borrowed gratuitously from Spring under ASL2.0.
*
* Added in local file cache ability for http and https urls.
*
* Set the system property: "drools.resource.urlcache" to a directory which can be written to and read from
* as a cache - so remote resources will be cached with last known good copies.
*/
public class UrlResource extends BaseResource
implements
InternalResource,
Externalizable {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static File CACHE_DIR = getCacheDir();
private URL url;
private long lastRead = -1;
private static final String DROOLS_RESOURCE_URLCACHE = "drools.resource.urlcache";
private String basicAuthentication = "disabled";
private String username = "";
private String password = "";
public UrlResource() {
}
public UrlResource(URL url) {
this.url = getCleanedUrl( url,
url.toString() );
setSourcePath( this.url.getPath() );
setResourceType( ResourceType.determineResourceType( this.url.getPath() ) );
}
public UrlResource(String path) {
try {
this.url = getCleanedUrl( new URL( path ),
path );
setSourcePath( this.url.getPath() );
setResourceType( ResourceType.determineResourceType( this.url.getPath() ) );
} catch ( MalformedURLException e ) {
throw new IllegalArgumentException( "'" + path + "' path is malformed",
e );
}
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( this.url );
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.url = (URL) in.readObject();
}
public String getBasicAuthentication() {
return basicAuthentication;
}
public void setBasicAuthentication(String basicAuthentication) {
this.basicAuthentication = basicAuthentication;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* This implementation opens an InputStream for the given URL.
* It sets the "UseCaches" flag to <code>false</code>,
* mainly to avoid jar file locking on Windows.
* @see java.net.URL#openConnection()
* @see java.net.URLConnection#setUseCaches(boolean)
* @see java.net.URLConnection#getInputStream()
*/
public InputStream getInputStream() throws IOException {
try {
long lastMod = grabLastMod();
if (lastMod == 0) {
//we will try the cache...
if (cacheFileExists()) return fromCache();
}
if (lastMod > 0 && lastMod > lastRead) {
- if (CACHE_DIR != null && url.getProtocol().equals("http") || url.getProtocol().equals("https")) {
+ if (CACHE_DIR != null && (url.getProtocol().equals("http") || url.getProtocol().equals("https"))) {
//lets grab a copy and cache it in case we need it in future...
cacheStream();
}
}
this.lastRead = lastMod;
return grabStream();
} catch (IOException e) {
if (cacheFileExists()) {
return fromCache();
} else {
throw e;
}
}
}
private boolean cacheFileExists() {
return CACHE_DIR != null && getCacheFile().exists();
}
private InputStream fromCache() throws FileNotFoundException, UnsupportedEncodingException {
File fi = getCacheFile();
return new FileInputStream(fi);
}
private File getCacheFile() {
try {
return new File(CACHE_DIR, URLEncoder.encode(this.url.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Save a copy in the local cache - in case remote source is not available in future.
*/
private void cacheStream() {
try {
File fi = getCacheFile();
if (fi.exists()) fi.delete();
FileOutputStream fout = new FileOutputStream(fi);
InputStream in = grabStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n;
while (-1 != (n = in.read(buffer))) {
fout.write(buffer, 0, n);
}
fout.flush();
fout.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private InputStream grabStream() throws IOException {
URLConnection con = this.url.openConnection();
con.setUseCaches( false );
if ( con instanceof HttpURLConnection) {
if ("enabled".equalsIgnoreCase(basicAuthentication)) {
String userpassword = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(userpassword.getBytes());
((HttpURLConnection) con).setRequestProperty("Authorization",
"Basic " + new String(authEncBytes));
}
}
return con.getInputStream();
}
public Reader getReader() throws IOException {
return new InputStreamReader( getInputStream() );
}
/**
* Determine a cleaned URL for the given original URL.
* @param originalUrl the original URL
* @param originalPath the original URL path
* @return the cleaned URL
*/
private URL getCleanedUrl(URL originalUrl,
String originalPath) {
try {
return new URL( StringUtils.cleanPath( originalPath ) );
} catch ( MalformedURLException ex ) {
// Cleaned URL path cannot be converted to URL
// -> take original URL.
return originalUrl;
}
}
public URL getURL() throws IOException {
return this.url;
}
public boolean hasURL() {
return true;
}
public File getFile() throws IOException {
try {
return new File( StringUtils.toURI( url.toString() ).getSchemeSpecificPart() );
} catch ( Exception e ) {
throw new RuntimeException( "Unable to get File for url " + this.url, e);
}
}
public long getLastModified() {
try {
long lm = grabLastMod();
//try the cache.
if (lm == 0 && cacheFileExists()) {
//OK we will return it from the local cached copy, as remote one isn't available..
return getCacheFile().lastModified();
}
return lm;
} catch ( IOException e ) {
//try the cache...
if (cacheFileExists()) {
//OK we will return it from the local cached copy, as remote one isn't available..
return getCacheFile().lastModified();
} else {
throw new RuntimeException( "Unable to get LastMofified for ClasspathResource",
e );
}
}
}
private long grabLastMod() throws IOException {
// use File if possible, as http rounds milliseconds on some machines, this fine level of granularity is only really an issue for testing
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504473
if ( "file".equals( url.getProtocol() ) ) {
File file = getFile();
return file.lastModified();
} else {
URLConnection conn = getURL().openConnection();
if ( conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).setRequestMethod( "HEAD" );
}
long date = conn.getLastModified();
if (date == 0) {
try {
date = Long.parseLong(conn.getHeaderField("lastModified"));
} catch (Exception e) { /* well, we tried ... */ }
}
return date;
}
}
public long getLastRead() {
return this.lastRead;
}
public boolean isDirectory() {
try {
URL url = getURL();
if ( "file".equals( url.getProtocol() ) ) {
File file = new File( StringUtils.toURI( url.toString() ).getSchemeSpecificPart() );
return file.isDirectory();
}
} catch ( Exception e ) {
// swallow as returned false
}
return false;
}
public Collection<Resource> listResources() {
try {
URL url = getURL();
if ( "file".equals( url.getProtocol() ) ) {
File dir = getFile();
List<Resource> resources = new ArrayList<Resource>();
for ( File file : dir.listFiles() ) {
resources.add( new FileSystemResource( file ) );
}
return resources;
}
} catch ( Exception e ) {
// swallow as we'll throw an exception anyway
}
throw new RuntimeException( "This Resource cannot be listed, or is not a directory" );
}
/**
* This implementation compares the underlying URL references.
*/
public boolean equals(Object obj) {
if ( obj == null ) {
return false;
}
return (obj == this || (obj instanceof UrlResource && this.url.equals( ((UrlResource) obj).url )));
}
/**
* This implementation returns the hash code of the underlying URL reference.
*/
public int hashCode() {
return this.url.hashCode();
}
public String toString() {
return "[UrlResource path='" + this.url.toString() + "']";
}
private static File getCacheDir() {
String root = System.getProperty(DROOLS_RESOURCE_URLCACHE, "NONE");
if (root.equals("NONE")) {
return null;
} else {
return new File(root);
}
}
}
| true | true |
public InputStream getInputStream() throws IOException {
try {
long lastMod = grabLastMod();
if (lastMod == 0) {
//we will try the cache...
if (cacheFileExists()) return fromCache();
}
if (lastMod > 0 && lastMod > lastRead) {
if (CACHE_DIR != null && url.getProtocol().equals("http") || url.getProtocol().equals("https")) {
//lets grab a copy and cache it in case we need it in future...
cacheStream();
}
}
this.lastRead = lastMod;
return grabStream();
} catch (IOException e) {
if (cacheFileExists()) {
return fromCache();
} else {
throw e;
}
}
}
|
public InputStream getInputStream() throws IOException {
try {
long lastMod = grabLastMod();
if (lastMod == 0) {
//we will try the cache...
if (cacheFileExists()) return fromCache();
}
if (lastMod > 0 && lastMod > lastRead) {
if (CACHE_DIR != null && (url.getProtocol().equals("http") || url.getProtocol().equals("https"))) {
//lets grab a copy and cache it in case we need it in future...
cacheStream();
}
}
this.lastRead = lastMod;
return grabStream();
} catch (IOException e) {
if (cacheFileExists()) {
return fromCache();
} else {
throw e;
}
}
}
|
diff --git a/src/net/mysticrealms/fireworks/scavengerhunt/ScavengerHunt.java b/src/net/mysticrealms/fireworks/scavengerhunt/ScavengerHunt.java
index ef3af7f..f8014da 100644
--- a/src/net/mysticrealms/fireworks/scavengerhunt/ScavengerHunt.java
+++ b/src/net/mysticrealms/fireworks/scavengerhunt/ScavengerHunt.java
@@ -1,326 +1,326 @@
package net.mysticrealms.fireworks.scavengerhunt;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Dye;
import org.bukkit.material.Wool;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class ScavengerHunt extends JavaPlugin {
public boolean isRunning;
public Configuration config;
public List<ItemStack> currentItems = new ArrayList<ItemStack>();
public List<ItemStack> items = new ArrayList<ItemStack>();
public List<ItemStack> rewards = new ArrayList<ItemStack>();
public Map<String, Map<EntityType, Integer>> ofMaps = new ConcurrentHashMap<String, Map<EntityType, Integer>>();
public Map<EntityType, Integer> mobs = new HashMap<EntityType, Integer>();
public int numOfItems = 0;
public int duration = 0;
public double money = 0;
public long end = 0;
public static Permission permission = null;
public static Economy economy = null;
@Override
public void onEnable() {
setupEconomy();
if (!loadConfig()) {
this.getLogger().severe("Something is wrong with the config! Disabling!");
this.setEnabled(false);
return;
}
this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new ScavengerInventory(this), 0, 40);
this.getServer().getPluginManager().registerEvents(new ScavengerListener(this), this);
}
private boolean setupEconomy() {
if (this.getServer().getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
this.getLogger().info("Vault found and loaded.");
return (economy != null);
}
economy = null;
this.getLogger().info("Vault not found - money reward will not be used.");
return false;
}
public boolean loadConfig() {
this.reloadConfig();
items.clear();
rewards.clear();
mobs.clear();
if (!new File(this.getDataFolder(), "config.yml").exists()) {
this.saveDefaultConfig();
}
config = this.getConfig();
if (config.isList("mobs")) {
- for (String i : config.getStringList("mobs")) {
+ for (Object i : config.getList("mobs", new ArrayList<String>())) {
try {
- final String[] parts = i.split(" ");
+ final String[] parts = i.toString().split(" ");
final int mobQuantity = Integer.parseInt(parts[1]);
final EntityType mobName = EntityType.fromName(parts[0]);
mobs.put(mobName, mobQuantity);
} catch (Exception e) {
return false;
}
}
}
if (config.isDouble("money"))
money = config.getDouble("money");
else if (config.isInt("money"))
money = config.getInt("money");
else
return false;
if (config.isInt("duration"))
duration = config.getInt("duration");
else
return false;
if (config.isInt("numOfItems"))
numOfItems = config.getInt("numOfItems");
else
return false;
if (config.isList("items")) {
- for (Object i : config.getStringList("items")) {
+ for (Object i : config.getList("items", new ArrayList<String>())) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.items.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.items.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.items.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
if (config.isList("rewards")) {
- for (Object i : config.getStringList("rewards")) {
+ for (Object i : config.getList("rewards", new ArrayList<String>())) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.rewards.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.rewards.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.rewards.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
return true;
}
public boolean isUsingMoney() {
if (this.money > 0)
return true;
else
return false;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("scavengerstart"))
runScavengerEvent();
if (cmd.getName().equalsIgnoreCase("scavengerstop"))
stopScavengerEvent();
if (cmd.getName().equalsIgnoreCase("scavengeritems"))
listScavengerEventItems(sender);
if (cmd.getName().equalsIgnoreCase("scavengerrewards"))
listScavengerEventRewards(sender);
if (cmd.getName().equalsIgnoreCase("scavengerhelp"))
listHelp(sender);
if (cmd.getName().equalsIgnoreCase("scavengerreload")) {
if (this.loadConfig())
sender.sendMessage(ChatColor.GOLD + "Config reloaded!");
else
sender.sendMessage(ChatColor.GOLD + "Config failed to reload!");
}
return true;
}
public void listHelp(CommandSender sender){
sender.sendMessage(ChatColor.DARK_RED + "== Scavenger Help Guide ==");
sender.sendMessage(ChatColor.GOLD + " * /scavengerItems - List items/objectives for current scavenger event.");
sender.sendMessage(ChatColor.GOLD + " * /scavengerRewards - List rewards for the winner.");
sender.sendMessage(ChatColor.DARK_GREEN + " * /scavengerStart - Start a scavenger event.");
sender.sendMessage(ChatColor.DARK_GREEN + " * /scavengerStop - End current scavenger vent.");
sender.sendMessage(ChatColor.DARK_GREEN + " * /scavengerReload - Reload the config.");
}
public void listScavengerEventItems(CommandSender sender) {
if (isRunning) {
if (!currentItems.isEmpty()) {
sender.sendMessage(ChatColor.DARK_RED + "Current scavenger items: ");
for (ItemStack i : currentItems) {
sender.sendMessage(ChatColor.GOLD + configToString(i));
}
}
if (!mobs.isEmpty()) {
sender.sendMessage(ChatColor.DARK_RED + "You need to kill: ");
for (Map.Entry<EntityType, Integer> entry : mobs.entrySet()) {
sender.sendMessage(ChatColor.GOLD + " * " + entry.getValue() + " " + entry.getKey().getName().toLowerCase().replace("_", " "));
}
}
} else {
sender.sendMessage(ChatColor.GOLD + "No scavenger event is currently running.");
}
}
public void listScavengerEventRewards(CommandSender sender) {
sender.sendMessage(ChatColor.GOLD + "Current scavenger rewards: ");
for (ItemStack i : rewards) {
sender.sendMessage(ChatColor.GOLD + configToString(i));
}
if (this.isUsingMoney())
sender.sendMessage(ChatColor.GOLD + " * " + economy.format(money));
}
public void stopScavengerEvent() {
this.getServer().broadcastMessage(ChatColor.DARK_RED + "Scavenger Hunt has ended with no winner.");
isRunning = false;
}
public void runScavengerEvent() {
this.currentItems.clear();
this.ofMaps.clear();
List<ItemStack> clone = new ArrayList<ItemStack>();
for (ItemStack i : items) {
clone.add(i);
}
Random r = new Random();
if (numOfItems <= 0) {
currentItems = clone;
} else {
for (int i = 0; i < numOfItems && !clone.isEmpty(); i++) {
currentItems.add(clone.remove(r.nextInt(clone.size())));
}
}
this.getServer().broadcastMessage(ChatColor.DARK_RED + "Scavenger Hunt is starting! Good luck!");
if (duration != 0) {
this.getServer().broadcastMessage(ChatColor.DARK_RED + "You have: " + ChatColor.GOLD + duration + " seconds!");
}
if (!currentItems.isEmpty()) {
this.getServer().broadcastMessage(ChatColor.DARK_RED + "You need to collect: ");
for (ItemStack i : currentItems) {
this.getServer().broadcastMessage(ChatColor.GOLD + configToString(i));
}
}
if (!mobs.isEmpty()) {
this.getServer().broadcastMessage(ChatColor.DARK_RED + "You need to kill: ");
for (Map.Entry<EntityType, Integer> entry : mobs.entrySet()) {
this.getServer().broadcastMessage(ChatColor.GOLD + " * " + entry.getValue() + " " + entry.getKey().getName().toLowerCase().replace("_", " "));
}
}
isRunning = true;
if (duration == 0) {
end = 0;
} else {
end = duration * 1000 + System.currentTimeMillis();
}
}
public synchronized Map<EntityType, Integer> getMap(String s) {
Map<EntityType, Integer> map = ofMaps.get(s);
if (map == null) {
map = new ConcurrentHashMap<EntityType, Integer>();
for (EntityType e : EntityType.values()) {
map.put(e, 0);
}
ofMaps.put(s, map);
}
return map;
}
public String configToString(ItemStack item) {
return " * " + item.getAmount() + " " + itemFormatter(item).toLowerCase().replace("_", " ");
}
public String itemFormatter(ItemStack item){
if (item.getType() == Material.WOOL){
return ((Wool)item.getData()).getColor().toString() + " wool";
}else if(item.getType() == Material.INK_SACK){
return ((Dye)item.getData()).getColor().toString() + " dye";
}else{
return item.getType().toString();
}
}
}
| false | true |
public boolean loadConfig() {
this.reloadConfig();
items.clear();
rewards.clear();
mobs.clear();
if (!new File(this.getDataFolder(), "config.yml").exists()) {
this.saveDefaultConfig();
}
config = this.getConfig();
if (config.isList("mobs")) {
for (String i : config.getStringList("mobs")) {
try {
final String[] parts = i.split(" ");
final int mobQuantity = Integer.parseInt(parts[1]);
final EntityType mobName = EntityType.fromName(parts[0]);
mobs.put(mobName, mobQuantity);
} catch (Exception e) {
return false;
}
}
}
if (config.isDouble("money"))
money = config.getDouble("money");
else if (config.isInt("money"))
money = config.getInt("money");
else
return false;
if (config.isInt("duration"))
duration = config.getInt("duration");
else
return false;
if (config.isInt("numOfItems"))
numOfItems = config.getInt("numOfItems");
else
return false;
if (config.isList("items")) {
for (Object i : config.getStringList("items")) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.items.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.items.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.items.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
if (config.isList("rewards")) {
for (Object i : config.getStringList("rewards")) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.rewards.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.rewards.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.rewards.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
return true;
}
|
public boolean loadConfig() {
this.reloadConfig();
items.clear();
rewards.clear();
mobs.clear();
if (!new File(this.getDataFolder(), "config.yml").exists()) {
this.saveDefaultConfig();
}
config = this.getConfig();
if (config.isList("mobs")) {
for (Object i : config.getList("mobs", new ArrayList<String>())) {
try {
final String[] parts = i.toString().split(" ");
final int mobQuantity = Integer.parseInt(parts[1]);
final EntityType mobName = EntityType.fromName(parts[0]);
mobs.put(mobName, mobQuantity);
} catch (Exception e) {
return false;
}
}
}
if (config.isDouble("money"))
money = config.getDouble("money");
else if (config.isInt("money"))
money = config.getInt("money");
else
return false;
if (config.isInt("duration"))
duration = config.getInt("duration");
else
return false;
if (config.isInt("numOfItems"))
numOfItems = config.getInt("numOfItems");
else
return false;
if (config.isList("items")) {
for (Object i : config.getList("items", new ArrayList<String>())) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.items.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.items.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.items.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
if (config.isList("rewards")) {
for (Object i : config.getList("rewards", new ArrayList<String>())) {
if (i instanceof String) {
final String[] parts = ((String) i).split(" ");
final int[] intParts = new int[parts.length];
for (int e = 0; e < parts.length; e++) {
try {
intParts[e] = Integer.parseInt(parts[e]);
} catch (final NumberFormatException exception) {
return false;
}
}
if (parts.length == 1) {
this.rewards.add(new ItemStack(intParts[0], 1));
} else if (parts.length == 2) {
this.rewards.add(new ItemStack(intParts[0], intParts[1]));
} else if (parts.length == 3) {
this.rewards.add(new ItemStack(intParts[0], intParts[1], (short) intParts[2]));
}
} else {
return false;
}
}
} else {
return false;
}
return true;
}
|
diff --git a/common-src/source/org/alt60m/servlet/LoggingFilter.java b/common-src/source/org/alt60m/servlet/LoggingFilter.java
index 650c3ed7..5cb8c579 100644
--- a/common-src/source/org/alt60m/servlet/LoggingFilter.java
+++ b/common-src/source/org/alt60m/servlet/LoggingFilter.java
@@ -1,129 +1,129 @@
package org.alt60m.servlet;
import java.io.IOException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.apache.log4j.NDC;
public class LoggingFilter implements Filter {
private final int MAX_HISTORY_SIZE = 15;
private static Log log = LogFactory.getLog(LoggingFilter.class);
public void destroy() {
log.debug("destroying Logging Filter");
}
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
String userIPAddress = req.getRemoteAddr();
MDC.put("userIPAddress", userIPAddress);
String machineName = InetAddress.getLocalHost().getHostName();
MDC.put("machineName", machineName);
String user = (String) req.getSession().getAttribute("userName");
if (user == null) {
user = (String) req.getSession().getAttribute("userLoggedIn");
}
if (user == null) {
user = "(anonymous)";
}
MDC.put("username", user);
NDC.push(user);
String actionName = req.getParameter("action");
if (actionName == null) {
actionName = "(not specified)";
}
MDC.put("action", actionName);
NDC.push(actionName);
Map<String, String> requestMap = getHashedRequest(req);
StringBuffer url = req.getRequestURL();
String lineSep = System.getProperty("line.separator");
lineSep = (lineSep == null ? "\n" : lineSep);
MDC.put("request", url.append(lineSep)
.append(requestMap.toString()).toString());
- List<String> history = (LinkedList<String>) req.getSession()
+ List<String> history = (List<String>) req.getSession()
.getAttribute("history");
if (history == null) {
history = Collections.synchronizedList(new LinkedList<String>());
req.getSession().setAttribute("history", history);
}
String currentTime = DateFormat.getTimeInstance().format(new Date());
String path = req.getRequestURI();
path = lineSep + path + " " + requestMap.toString() + " [" + currentTime + "]" + lineSep;
history.add(path);
if (history.size() > MAX_HISTORY_SIZE) {
history.remove(0);
}
Map<String, Object> sessionCopy = getHashedSession(req);
MDC.put("session", sessionCopy.toString());
log.debug("Forwarding request for " + req.getRequestURI());
filterChain.doFilter(request, response);
} finally {
NDC.pop();
NDC.pop();
MDC.remove("username");
MDC.remove("action");
MDC.remove("session");
MDC.remove("request");
MDC.remove("userIPAddress");
MDC.remove("machineName");
}
}
private Map<String, Object> getHashedSession(HttpServletRequest req) {
Map<String, Object> sessionCopy = new HashMap<String, Object>();
for (Enumeration<String> attributeNames = (Enumeration<String>) req
.getSession().getAttributeNames(); attributeNames
.hasMoreElements();) {
String attributeName = attributeNames.nextElement();
sessionCopy.put(attributeName, req.getSession().getAttribute(
attributeName));
}
return sessionCopy;
}
public void init(FilterConfig config) throws ServletException {
log.debug("Starting logging filter");
}
public Map<String, String> getHashedRequest(HttpServletRequest request) {
Map<String, String> h = new HashMap<String, String>();
for (Enumeration enumer = request.getParameterNames(); enumer
.hasMoreElements();) {
String key = (String) enumer.nextElement();
h.put(key, request.getParameter(key));
}
return h;
}
}
| true | true |
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
String userIPAddress = req.getRemoteAddr();
MDC.put("userIPAddress", userIPAddress);
String machineName = InetAddress.getLocalHost().getHostName();
MDC.put("machineName", machineName);
String user = (String) req.getSession().getAttribute("userName");
if (user == null) {
user = (String) req.getSession().getAttribute("userLoggedIn");
}
if (user == null) {
user = "(anonymous)";
}
MDC.put("username", user);
NDC.push(user);
String actionName = req.getParameter("action");
if (actionName == null) {
actionName = "(not specified)";
}
MDC.put("action", actionName);
NDC.push(actionName);
Map<String, String> requestMap = getHashedRequest(req);
StringBuffer url = req.getRequestURL();
String lineSep = System.getProperty("line.separator");
lineSep = (lineSep == null ? "\n" : lineSep);
MDC.put("request", url.append(lineSep)
.append(requestMap.toString()).toString());
List<String> history = (LinkedList<String>) req.getSession()
.getAttribute("history");
if (history == null) {
history = Collections.synchronizedList(new LinkedList<String>());
req.getSession().setAttribute("history", history);
}
String currentTime = DateFormat.getTimeInstance().format(new Date());
String path = req.getRequestURI();
path = lineSep + path + " " + requestMap.toString() + " [" + currentTime + "]" + lineSep;
history.add(path);
if (history.size() > MAX_HISTORY_SIZE) {
history.remove(0);
}
Map<String, Object> sessionCopy = getHashedSession(req);
MDC.put("session", sessionCopy.toString());
log.debug("Forwarding request for " + req.getRequestURI());
filterChain.doFilter(request, response);
} finally {
NDC.pop();
NDC.pop();
MDC.remove("username");
MDC.remove("action");
MDC.remove("session");
MDC.remove("request");
MDC.remove("userIPAddress");
MDC.remove("machineName");
}
}
|
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
String userIPAddress = req.getRemoteAddr();
MDC.put("userIPAddress", userIPAddress);
String machineName = InetAddress.getLocalHost().getHostName();
MDC.put("machineName", machineName);
String user = (String) req.getSession().getAttribute("userName");
if (user == null) {
user = (String) req.getSession().getAttribute("userLoggedIn");
}
if (user == null) {
user = "(anonymous)";
}
MDC.put("username", user);
NDC.push(user);
String actionName = req.getParameter("action");
if (actionName == null) {
actionName = "(not specified)";
}
MDC.put("action", actionName);
NDC.push(actionName);
Map<String, String> requestMap = getHashedRequest(req);
StringBuffer url = req.getRequestURL();
String lineSep = System.getProperty("line.separator");
lineSep = (lineSep == null ? "\n" : lineSep);
MDC.put("request", url.append(lineSep)
.append(requestMap.toString()).toString());
List<String> history = (List<String>) req.getSession()
.getAttribute("history");
if (history == null) {
history = Collections.synchronizedList(new LinkedList<String>());
req.getSession().setAttribute("history", history);
}
String currentTime = DateFormat.getTimeInstance().format(new Date());
String path = req.getRequestURI();
path = lineSep + path + " " + requestMap.toString() + " [" + currentTime + "]" + lineSep;
history.add(path);
if (history.size() > MAX_HISTORY_SIZE) {
history.remove(0);
}
Map<String, Object> sessionCopy = getHashedSession(req);
MDC.put("session", sessionCopy.toString());
log.debug("Forwarding request for " + req.getRequestURI());
filterChain.doFilter(request, response);
} finally {
NDC.pop();
NDC.pop();
MDC.remove("username");
MDC.remove("action");
MDC.remove("session");
MDC.remove("request");
MDC.remove("userIPAddress");
MDC.remove("machineName");
}
}
|
diff --git a/src/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java b/src/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java
index 1d350a5c..27cd6943 100644
--- a/src/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java
+++ b/src/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java
@@ -1,159 +1,159 @@
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* ===========================================================================
*
* (C) Copyright IBM Corp. 2003 All Rights Reserved.
*
* ===========================================================================
*/
/*
* Portions copyright 2005 Sun Microsystems, Inc. All rights reserved.
*/
/*
* $Id$
*/
package org.jcp.xml.dsig.internal.dom;
import java.util.*;
import java.security.*;
import javax.xml.crypto.dsig.*;
/**
* The XMLDSig RI Provider.
*
* @author Joyce Leung
*/
/**
* Defines the XMLDSigRI provider.
*/
public final class XMLDSigRI extends Provider {
static final long serialVersionUID = -5049765099299494554L;
private static final String INFO = "Apache Santuario XMLDSig " +
"(DOM XMLSignatureFactory; DOM KeyInfoFactory)";
public XMLDSigRI() {
/* We are the XMLDSig provider */
- super("XMLDSig", 1.44, INFO);
+ super("XMLDSig", 1.45, INFO);
final Map map = new HashMap();
map.put("XMLSignatureFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
map.put("KeyInfoFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory");
// Inclusive C14N
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE",
CanonicalizationMethod.INCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE +
" MechanismType", "DOM");
// InclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Inclusive C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11" +
" MechanismType", "DOM");
// InclusiveWithComments C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments" +
" MechanismType", "DOM");
// Exclusive C14N
map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE",
CanonicalizationMethod.EXCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE +
" MechanismType", "DOM");
// ExclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Base64 Transform
map.put((String) "TransformService." + Transform.BASE64,
"org.jcp.xml.dsig.internal.dom.DOMBase64Transform");
map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64);
map.put((String) "TransformService." + Transform.BASE64 +
" MechanismType", "DOM");
// Enveloped Transform
map.put((String) "TransformService." + Transform.ENVELOPED,
"org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform");
map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED);
map.put((String) "TransformService." + Transform.ENVELOPED +
" MechanismType", "DOM");
// XPath2 Transform
map.put((String) "TransformService." + Transform.XPATH2,
"org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform");
map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2);
map.put((String) "TransformService." + Transform.XPATH2 +
" MechanismType", "DOM");
// XPath Transform
map.put((String) "TransformService." + Transform.XPATH,
"org.jcp.xml.dsig.internal.dom.DOMXPathTransform");
map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH);
map.put((String) "TransformService." + Transform.XPATH +
" MechanismType", "DOM");
// XSLT Transform
map.put((String) "TransformService." + Transform.XSLT,
"org.jcp.xml.dsig.internal.dom.DOMXSLTTransform");
map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT);
map.put((String) "TransformService." + Transform.XSLT +
" MechanismType", "DOM");
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
putAll(map);
return null;
}
});
}
}
| true | true |
public XMLDSigRI() {
/* We are the XMLDSig provider */
super("XMLDSig", 1.44, INFO);
final Map map = new HashMap();
map.put("XMLSignatureFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
map.put("KeyInfoFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory");
// Inclusive C14N
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE",
CanonicalizationMethod.INCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE +
" MechanismType", "DOM");
// InclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Inclusive C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11" +
" MechanismType", "DOM");
// InclusiveWithComments C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments" +
" MechanismType", "DOM");
// Exclusive C14N
map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE",
CanonicalizationMethod.EXCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE +
" MechanismType", "DOM");
// ExclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Base64 Transform
map.put((String) "TransformService." + Transform.BASE64,
"org.jcp.xml.dsig.internal.dom.DOMBase64Transform");
map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64);
map.put((String) "TransformService." + Transform.BASE64 +
" MechanismType", "DOM");
// Enveloped Transform
map.put((String) "TransformService." + Transform.ENVELOPED,
"org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform");
map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED);
map.put((String) "TransformService." + Transform.ENVELOPED +
" MechanismType", "DOM");
// XPath2 Transform
map.put((String) "TransformService." + Transform.XPATH2,
"org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform");
map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2);
map.put((String) "TransformService." + Transform.XPATH2 +
" MechanismType", "DOM");
// XPath Transform
map.put((String) "TransformService." + Transform.XPATH,
"org.jcp.xml.dsig.internal.dom.DOMXPathTransform");
map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH);
map.put((String) "TransformService." + Transform.XPATH +
" MechanismType", "DOM");
// XSLT Transform
map.put((String) "TransformService." + Transform.XSLT,
"org.jcp.xml.dsig.internal.dom.DOMXSLTTransform");
map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT);
map.put((String) "TransformService." + Transform.XSLT +
" MechanismType", "DOM");
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
putAll(map);
return null;
}
});
}
|
public XMLDSigRI() {
/* We are the XMLDSig provider */
super("XMLDSig", 1.45, INFO);
final Map map = new HashMap();
map.put("XMLSignatureFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
map.put("KeyInfoFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory");
// Inclusive C14N
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE",
CanonicalizationMethod.INCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE +
" MechanismType", "DOM");
// InclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Inclusive C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11" +
" MechanismType", "DOM");
// InclusiveWithComments C14N 1.1
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put((String)"TransformService." +
"http://www.w3.org/2006/12/xml-c14n11#WithComments" +
" MechanismType", "DOM");
// Exclusive C14N
map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE",
CanonicalizationMethod.EXCLUSIVE);
map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE +
" MechanismType", "DOM");
// ExclusiveWithComments C14N
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
map.put((String) "TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Base64 Transform
map.put((String) "TransformService." + Transform.BASE64,
"org.jcp.xml.dsig.internal.dom.DOMBase64Transform");
map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64);
map.put((String) "TransformService." + Transform.BASE64 +
" MechanismType", "DOM");
// Enveloped Transform
map.put((String) "TransformService." + Transform.ENVELOPED,
"org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform");
map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED);
map.put((String) "TransformService." + Transform.ENVELOPED +
" MechanismType", "DOM");
// XPath2 Transform
map.put((String) "TransformService." + Transform.XPATH2,
"org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform");
map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2);
map.put((String) "TransformService." + Transform.XPATH2 +
" MechanismType", "DOM");
// XPath Transform
map.put((String) "TransformService." + Transform.XPATH,
"org.jcp.xml.dsig.internal.dom.DOMXPathTransform");
map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH);
map.put((String) "TransformService." + Transform.XPATH +
" MechanismType", "DOM");
// XSLT Transform
map.put((String) "TransformService." + Transform.XSLT,
"org.jcp.xml.dsig.internal.dom.DOMXSLTTransform");
map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT);
map.put((String) "TransformService." + Transform.XSLT +
" MechanismType", "DOM");
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
putAll(map);
return null;
}
});
}
|
diff --git a/KBAccess/kbaccess-webapp/src/main/java/org/opens/kbaccess/controller/TestcaseController.java b/KBAccess/kbaccess-webapp/src/main/java/org/opens/kbaccess/controller/TestcaseController.java
index 750b895..fe579f0 100644
--- a/KBAccess/kbaccess-webapp/src/main/java/org/opens/kbaccess/controller/TestcaseController.java
+++ b/KBAccess/kbaccess-webapp/src/main/java/org/opens/kbaccess/controller/TestcaseController.java
@@ -1,589 +1,592 @@
/*
* KBAccess - Collaborative database of accessibility examples
* Copyright (C) 2012-2016 Open-S Company
*
* This file is part of KBAccess.
*
* KBAccess is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.kbaccess.controller;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.logging.LogFactory;
import org.opens.kbaccess.command.DeleteTestcaseCommand;
import org.opens.kbaccess.command.EditTestcaseCommand;
import org.opens.kbaccess.command.NewTestcaseCommand;
import org.opens.kbaccess.controller.utils.AMailerController;
import org.opens.kbaccess.entity.authorization.Account;
import org.opens.kbaccess.entity.reference.*;
import org.opens.kbaccess.entity.service.subject.WebarchiveDataService;
import org.opens.kbaccess.entity.subject.Testcase;
import org.opens.kbaccess.entity.subject.Webarchive;
import org.opens.kbaccess.keystore.FormKeyStore;
import org.opens.kbaccess.keystore.MessageKeyStore;
import org.opens.kbaccess.keystore.ModelAttributeKeyStore;
import org.opens.kbaccess.presentation.AccountPresentation;
import org.opens.kbaccess.presentation.TestcasePresentation;
import org.opens.kbaccess.utils.AccountUtils;
import org.opens.kbaccess.validator.EditTestcaseValidator;
import org.opens.kbaccess.validator.NewTestcaseValidator;
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.annotation.*;
/**
*
* @author bcareil
*/
@Controller
@RequestMapping("/example/")
public class TestcaseController extends AMailerController {
@Autowired
private WebarchiveDataService webarchiveDataService;
@Autowired
private WebarchiveController webarchiveController;
/*
* Private methods
*/
private Map<String, String> buildMapFromSearchParameters(
Reference reference,
Criterion criterion,
Theme theme,
Test test,
Level level,
Result result
) {
Map<String, String> parametersMap = new LinkedHashMap<String, String>();
// building criteria list
if (reference != null) {
parametersMap.put("accessibility.reference", reference.getLabel());
}
if (theme != null) {
parametersMap.put("accessibility.theme", theme.getLabel());
}
if (criterion != null) {
parametersMap.put("accessibility.criterion", criterion.getLabel());
}
if (test != null) {
parametersMap.put("accessibility.test", test.getLabel());
}
if (level != null) {
parametersMap.put("accessibility.level", level.getCode());
}
if (result != null) {
parametersMap.put("result", result.getCode());
}
// post process criteria list
if (parametersMap.isEmpty()) {
// no criteria
parametersMap.put("testcase.searchAllTestcasesTitle", reference.getLabel());
}
return parametersMap;
}
private String displayAddTestcaseForm(Model model, NewTestcaseCommand newTestcaseCommand) {
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// create the form command
model.addAttribute("testByRef", getTestByRef());
model.addAttribute("resultList", getResults());
model.addAttribute("newTestcaseCommand", newTestcaseCommand);
return "testcase/add";
}
private String displayAttachWebarchiveForm(Model model, NewTestcaseCommand newTestcaseCommand) {
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// create the form command
model.addAttribute("webarchiveList", webarchiveDataService.findAll());
model.addAttribute("newTestcaseCommand", newTestcaseCommand);
return "testcase/add-webarchive";
}
private String displayEditTestcaseForm(Model model, EditTestcaseCommand editTestcaseCommand) {
// handle login form and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// create form
model.addAttribute("testByRef", getTestByRef());
model.addAttribute("resultList", getResults());
model.addAttribute("editTestcaseCommand", editTestcaseCommand);
return "testcase/edit-details";
}
private String displayTestcaseDetails(Model model, Testcase testcase) {
TestcasePresentation testcasePresentation = new TestcasePresentation(testcase, true);
// handle form login
handleUserLoginForm(model);
// handle breadcrumb
handleBreadcrumbTrail(model);
model.addAttribute("testcase", testcasePresentation);
return "testcase/details";
}
private String displayTestcaseError(Model model, String errorMessage) {
// handle login form and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// create form
model.addAttribute("errorMessage", errorMessage);
return "testcase/error";
}
/*
* Endpoints
*/
@RequestMapping(value="search-by-url")
public String searchByUrlHandler(Model model) {
// handle login form and breadcrumb trail
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
return "testcase/search-by-url";
}
@RequestMapping(value={"search", "result"}, method=RequestMethod.GET)
public String searchHandler(Model model) {
// handle login form, breadcrumb and search form
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
handleTestcaseSearchForm(model);
return "testcase/search";
}
@RequestMapping(value="list")
public String listHandler(
Model model,
@RequestParam(value="account", required=false) Long idAccount,
@RequestParam(value="reference", required=false) Long idReference,
@RequestParam(value="theme", required=false) Long idTheme,
@RequestParam(value="level", required=false) Long idLevel,
@RequestParam(value="criterion", required=false) Long idCriterion,
@RequestParam(value="test", required=false) Long idTest,
@RequestParam(value="result", required=false) Long idResult
) {
Collection<TestcasePresentation> testcases;
String contextOfRequest = null;
boolean joker;
Reference reference;
Theme theme;
Level level;
Criterion criterion;
Test test;
Result result;
// fetch all testcases ?
joker = (idAccount == null
&& idReference == null
&& idTheme == null
&& idLevel == null
&& idCriterion == null
&& idTest == null
&& idResult == null
);
// fetch entities and set title and H1
if (joker) {
testcases = TestcasePresentation.fromCollection(
(Collection) testcaseDataService.findAll(),
true
);
contextOfRequest = "allTestcases";
handleBreadcrumbTrail(model);
// fetch the testcases of a precise user
} else if (idAccount != null) {
String authorDisplayedName;
Account account = accountDataService.read(idAccount);
authorDisplayedName = AccountPresentation.generateDisplayedName(account);
testcases = TestcasePresentation.fromCollection(
testcaseDataService.getAllFromAccount(account),
true
);
contextOfRequest = "userTestcases";
handleBreadcrumbTrail(model);
model.addAttribute("account", new AccountPresentation(account, accountDataService));
// All other requests combinations
} else {
reference = (idReference == null ? null : referenceDataService.read(idReference));
theme = (idTheme == null ? null : themeDataService.read(idTheme));
level = (idLevel == null ? null : levelDataService.read(idLevel));
criterion = (idCriterion == null ? null : criterionDataService.read(idCriterion));
test = (idTest == null ? null : testDataService.read(idTest));
result = (idResult == null ? null : resultDataService.read(idResult));
testcases = TestcasePresentation.fromCollection(
testcaseDataService.getAllFromUserSelection(reference, criterion, theme, test, level, result),
true
);
handleBreadcrumbTrail(model);
model.addAttribute("parameterMap", buildMapFromSearchParameters(reference, criterion, theme, test, level, result));
}
// handle login and breadcrumb
handleUserLoginForm(model);
model.addAttribute("contextOfRequest", contextOfRequest);
// result list
model.addAttribute(ModelAttributeKeyStore.TESTCASE_LIST_KEY, testcases);
model.addAttribute("showTestcaseSearchForm", false);
return "testcase/list";
}
/*
* Handlers to add a testcase
*/
@RequestMapping(value={"add", "add-finalize"}, method=RequestMethod.GET)
public String addHandler(Model model) {
return displayAddTestcaseForm(model, new NewTestcaseCommand());
}
@RequestMapping(value="add", method=RequestMethod.POST)
public String addHandler(
@ModelAttribute("newTestcaseCommand") NewTestcaseCommand testcaseCommand,
BindingResult result,
Model model
) {
NewTestcaseValidator newTestcaseValidator = new NewTestcaseValidator(
criterionDataService,
testDataService,
resultDataService,
webarchiveDataService,
NewTestcaseValidator.Step.STEP_TESTCASE
);
// validate command
newTestcaseValidator.validate(testcaseCommand, result);
if (result.hasErrors()) {
// return to the first step
return displayAddTestcaseForm(model, testcaseCommand);
}
// display the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
@RequestMapping(value="add-finalize", method=RequestMethod.POST)
public String finalizeAddHandler(
@ModelAttribute("newTestcaseCommand") NewTestcaseCommand testcaseCommand,
BindingResult result,
Model model
) {
Webarchive webarchive;
Account currentUser;
Testcase newTestcase;
TestcasePresentation testcasePresentation;
NewTestcaseValidator newTestcaseValidator = new NewTestcaseValidator(
criterionDataService,
testDataService,
resultDataService,
webarchiveDataService,
NewTestcaseValidator.Step.STEP_WEBARCHIVE
);
// validate command
newTestcaseValidator.validate(testcaseCommand, result);
if (result.hasErrors()) {
if (result.hasFieldErrors(FormKeyStore.ID_TEST_KEY) || result.hasFieldErrors(FormKeyStore.ID_RESULT_KEY)) {
// return to the first step if we have an error on the test or result id
return displayAddTestcaseForm(model, testcaseCommand);
} else {
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
}
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// sanity check
currentUser = AccountUtils.getInstance().getCurrentUser();
if (currentUser == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/add-finalize. Check spring security configuration.");
return "guest/login";
}
// get webarchive
if (!testcaseCommand.getCreateWebarchive()) {
webarchive = webarchiveDataService.read(testcaseCommand.getIdWebarchive());
} else {
webarchive = webarchiveController.createWebarchive(
currentUser,
testcaseCommand.getUrlNewWebarchive(),
testcaseCommand.getDescriptionNewWebarchive()
);
if (webarchive != null) {
// persist the webarchive
webarchiveDataService.saveOrUpdate(webarchive);
} // a null webarchive is handled below
}
// sanity check
if (webarchive == null) {
// most of the time, if the webarchive is null, it means its creation
// fails.
- testcaseCommand.setGeneralErrorMessage("Unable to create the webarchive.");
+ model.addAttribute(
+ FormKeyStore.GENERAL_ERROR_MESSAGE_KEY,
+ MessageKeyStore.CANNOT_CREATE_WEBARCHIVE
+ );
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
// create testcase
if (testcaseCommand.getIdTest() != null) {
newTestcase = testcaseDataService.createFromTest(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
testDataService.read(testcaseCommand.getIdTest()),
testcaseCommand.getDescription()
);
} else {
newTestcase = testcaseDataService.createFromCriterion(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
criterionDataService.read(testcaseCommand.getIdCriterion()),
testcaseCommand.getDescription()
);
}
// persist testcase
newTestcase.setTitle("title"); // FIXME: title is not used anymore
testcaseDataService.saveOrUpdate(newTestcase);
// email notification
sendTestcaseCreationNotification(newTestcase);
// display testcase
testcasePresentation = new TestcasePresentation(newTestcase, true);
model.addAttribute("testcase", testcasePresentation);
return "testcase/add-summary";
}
/*
* Handlers to modify a testcase
*/
@RequestMapping(value="edit-details/{id}/*", method=RequestMethod.GET)
public String editDetailsHandler(
@PathVariable("id") Long id,
Model model
) {
EditTestcaseCommand editTestcaseCommand;
Testcase testcase = null;
Account account;
TestcasePresentation testcasePresentation;
// fetch test case
try {
testcase = testcaseDataService.read(id, true);
} catch (NullPointerException e) {
LogFactory.getLog(TestcaseController.class.getName()).debug("testcase doesn't exist");
}
if (testcase == null) {
LogFactory.getLog(TestcaseController.class.getName()).debug("testcase is null");
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
// check permissions
account = AccountUtils.getInstance().getCurrentUser();
if (account == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/edit-details. Check spring security configuration.");
return "guest/login";
} else if (!AccountUtils.getInstance().currentUserhasPermissionToEditTestcase(testcase)) {
return displayTestcaseError(model, MessageKeyStore.NOT_AUTHORIZED_TO_EDIT_TESTCASE);
}
testcasePresentation = new TestcasePresentation(testcase, true);
model.addAttribute("testcase", testcasePresentation);
// create form
editTestcaseCommand = new EditTestcaseCommand(testcase);
return displayEditTestcaseForm(model, editTestcaseCommand);
}
@RequestMapping(value="edit-details/{id}/*", method=RequestMethod.POST)
public String editDetailsHandler(
@ModelAttribute("editTestcaseCommand") EditTestcaseCommand editTestcaseCommand,
BindingResult result,
Model model
) {
Testcase testcase;
Account account;
EditTestcaseValidator testcaseValidator = new EditTestcaseValidator(
testcaseDataService,
resultDataService,
testDataService
);
// fetch account
account = AccountUtils.getInstance().getCurrentUser();
if (account == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached edit-details. Check spring security configuration.");
return "guest/login";
}
// fetch testcase
testcase = testcaseDataService.read(editTestcaseCommand.getId(), true);
if (testcase == null) {
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
// check permisions
if (!AccountUtils.getInstance().currentUserhasPermissionToEditTestcase(testcase)) {
return displayTestcaseError(model, MessageKeyStore.NOT_AUTHORIZED_TO_EDIT_TESTCASE);
}
// validate form
testcaseValidator.validate(editTestcaseCommand, result);
if (result.hasErrors()) {
return displayEditTestcaseForm(model, editTestcaseCommand);
}
// update testcase
editTestcaseCommand.update(testcase, criterionDataService, testDataService, testresultDataservice, resultDataService);
testcaseDataService.saveOrUpdate(testcase);
// confirmation message
model.addAttribute("successMessage", MessageKeyStore.TESTCASE_EDITED);
return displayTestcaseDetails(model, testcase);
}
@RequestMapping(value="details/{id}/*", method={RequestMethod.GET, RequestMethod.POST})
public String detailsHandler(
@PathVariable("id") Long id,
Model model
) {
Testcase testcase;
// fetch testcase
try {
testcase = testcaseDataService.read(id, true);
} catch (NullPointerException e) {
LogFactory.getLog(TestcaseController.class.getName()).debug("testcase doesn't exist");
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
return displayTestcaseDetails(model, testcase);
}
/*
* Handlers to delete a testcase
*/
@RequestMapping(value="delete/{id}/*", method=RequestMethod.GET)
public String deleteHandler(
@PathVariable("id") Long id,
Model model
) {
DeleteTestcaseCommand deleteTestcaseCommand;
Testcase testcase;
Account account;
TestcasePresentation testcasePresentation;
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// fetch test case
try {
testcase = testcaseDataService.read(id, true);
} catch (NullPointerException e) {
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
// check permissions
account = AccountUtils.getInstance().getCurrentUser();
if (account == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/delete. Check spring security configuration.");
return "guest/login";
} else if (!AccountUtils.getInstance().currentUserhasPermissionToEditTestcase(testcase)) {
return displayTestcaseError(model, MessageKeyStore.NOT_AUTHORIZED_TO_DELETE_TESTCASE);
}
deleteTestcaseCommand = new DeleteTestcaseCommand(testcase);
testcasePresentation = new TestcasePresentation(testcase, true);
model.addAttribute("deleteTestcaseCommand", deleteTestcaseCommand);
model.addAttribute("testcase", testcasePresentation);
return "testcase/delete";
}
@RequestMapping(value="delete/{id}/*", method=RequestMethod.POST)
public String confirmDeleteHandler(
@ModelAttribute("deleteTestcaseCommand") DeleteTestcaseCommand deleteTestcaseCommand,
BindingResult result,
Model model
) {
Testcase testcase;
Account account;
TestcasePresentation testcasePresentation;
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// fetch test case
try {
testcase = testcaseDataService.read(deleteTestcaseCommand.getId(), true);
} catch (NullPointerException e) {
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
if (testcase == null) {
return displayTestcaseError(model, MessageKeyStore.TESTCASE_DOESNT_EXIST);
}
// check permissions
account = AccountUtils.getInstance().getCurrentUser();
if (account == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/delete. Check spring security configuration.");
return "guest/login";
} else if (!AccountUtils.getInstance().currentUserhasPermissionToEditTestcase(testcase)) {
return displayTestcaseError(model, MessageKeyStore.NOT_AUTHORIZED_TO_DELETE_TESTCASE);
}
// delete the testcase
testcaseDataService.delete(testcase.getId());
testcasePresentation = new TestcasePresentation(testcase, true);
model.addAttribute("testcase", testcasePresentation);
// confirmation message
model.addAttribute("successMessage", MessageKeyStore.TESTCASE_DELETED);
return "testcase/delete";
}
/*
* Accessors
*/
public WebarchiveDataService getWebarchiveDataService() {
return webarchiveDataService;
}
public void setWebarchiveDataService(WebarchiveDataService webarchiveDataService) {
this.webarchiveDataService = webarchiveDataService;
}
}
| true | true |
public String finalizeAddHandler(
@ModelAttribute("newTestcaseCommand") NewTestcaseCommand testcaseCommand,
BindingResult result,
Model model
) {
Webarchive webarchive;
Account currentUser;
Testcase newTestcase;
TestcasePresentation testcasePresentation;
NewTestcaseValidator newTestcaseValidator = new NewTestcaseValidator(
criterionDataService,
testDataService,
resultDataService,
webarchiveDataService,
NewTestcaseValidator.Step.STEP_WEBARCHIVE
);
// validate command
newTestcaseValidator.validate(testcaseCommand, result);
if (result.hasErrors()) {
if (result.hasFieldErrors(FormKeyStore.ID_TEST_KEY) || result.hasFieldErrors(FormKeyStore.ID_RESULT_KEY)) {
// return to the first step if we have an error on the test or result id
return displayAddTestcaseForm(model, testcaseCommand);
} else {
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
}
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// sanity check
currentUser = AccountUtils.getInstance().getCurrentUser();
if (currentUser == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/add-finalize. Check spring security configuration.");
return "guest/login";
}
// get webarchive
if (!testcaseCommand.getCreateWebarchive()) {
webarchive = webarchiveDataService.read(testcaseCommand.getIdWebarchive());
} else {
webarchive = webarchiveController.createWebarchive(
currentUser,
testcaseCommand.getUrlNewWebarchive(),
testcaseCommand.getDescriptionNewWebarchive()
);
if (webarchive != null) {
// persist the webarchive
webarchiveDataService.saveOrUpdate(webarchive);
} // a null webarchive is handled below
}
// sanity check
if (webarchive == null) {
// most of the time, if the webarchive is null, it means its creation
// fails.
testcaseCommand.setGeneralErrorMessage("Unable to create the webarchive.");
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
// create testcase
if (testcaseCommand.getIdTest() != null) {
newTestcase = testcaseDataService.createFromTest(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
testDataService.read(testcaseCommand.getIdTest()),
testcaseCommand.getDescription()
);
} else {
newTestcase = testcaseDataService.createFromCriterion(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
criterionDataService.read(testcaseCommand.getIdCriterion()),
testcaseCommand.getDescription()
);
}
// persist testcase
newTestcase.setTitle("title"); // FIXME: title is not used anymore
testcaseDataService.saveOrUpdate(newTestcase);
// email notification
sendTestcaseCreationNotification(newTestcase);
// display testcase
testcasePresentation = new TestcasePresentation(newTestcase, true);
model.addAttribute("testcase", testcasePresentation);
return "testcase/add-summary";
}
|
public String finalizeAddHandler(
@ModelAttribute("newTestcaseCommand") NewTestcaseCommand testcaseCommand,
BindingResult result,
Model model
) {
Webarchive webarchive;
Account currentUser;
Testcase newTestcase;
TestcasePresentation testcasePresentation;
NewTestcaseValidator newTestcaseValidator = new NewTestcaseValidator(
criterionDataService,
testDataService,
resultDataService,
webarchiveDataService,
NewTestcaseValidator.Step.STEP_WEBARCHIVE
);
// validate command
newTestcaseValidator.validate(testcaseCommand, result);
if (result.hasErrors()) {
if (result.hasFieldErrors(FormKeyStore.ID_TEST_KEY) || result.hasFieldErrors(FormKeyStore.ID_RESULT_KEY)) {
// return to the first step if we have an error on the test or result id
return displayAddTestcaseForm(model, testcaseCommand);
} else {
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
}
// handle login and breadcrumb
handleUserLoginForm(model);
handleBreadcrumbTrail(model);
// sanity check
currentUser = AccountUtils.getInstance().getCurrentUser();
if (currentUser == null) {
LogFactory.getLog(TestcaseController.class).error("An unauthentified user reached testcase/add-finalize. Check spring security configuration.");
return "guest/login";
}
// get webarchive
if (!testcaseCommand.getCreateWebarchive()) {
webarchive = webarchiveDataService.read(testcaseCommand.getIdWebarchive());
} else {
webarchive = webarchiveController.createWebarchive(
currentUser,
testcaseCommand.getUrlNewWebarchive(),
testcaseCommand.getDescriptionNewWebarchive()
);
if (webarchive != null) {
// persist the webarchive
webarchiveDataService.saveOrUpdate(webarchive);
} // a null webarchive is handled below
}
// sanity check
if (webarchive == null) {
// most of the time, if the webarchive is null, it means its creation
// fails.
model.addAttribute(
FormKeyStore.GENERAL_ERROR_MESSAGE_KEY,
MessageKeyStore.CANNOT_CREATE_WEBARCHIVE
);
// return to the second step
return displayAttachWebarchiveForm(model, testcaseCommand);
}
// create testcase
if (testcaseCommand.getIdTest() != null) {
newTestcase = testcaseDataService.createFromTest(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
testDataService.read(testcaseCommand.getIdTest()),
testcaseCommand.getDescription()
);
} else {
newTestcase = testcaseDataService.createFromCriterion(
currentUser,
webarchive,
resultDataService.read(testcaseCommand.getIdResult()),
criterionDataService.read(testcaseCommand.getIdCriterion()),
testcaseCommand.getDescription()
);
}
// persist testcase
newTestcase.setTitle("title"); // FIXME: title is not used anymore
testcaseDataService.saveOrUpdate(newTestcase);
// email notification
sendTestcaseCreationNotification(newTestcase);
// display testcase
testcasePresentation = new TestcasePresentation(newTestcase, true);
model.addAttribute("testcase", testcasePresentation);
return "testcase/add-summary";
}
|
diff --git a/src/test/java/org/kevoree/resolver/MavenVersionResolverTest.java b/src/test/java/org/kevoree/resolver/MavenVersionResolverTest.java
index f06f976..84e5806 100644
--- a/src/test/java/org/kevoree/resolver/MavenVersionResolverTest.java
+++ b/src/test/java/org/kevoree/resolver/MavenVersionResolverTest.java
@@ -1,97 +1,97 @@
package org.kevoree.resolver;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
/**
* User: Erwan Daubert - [email protected]
* Date: 18/06/13
* Time: 14:02
*
* @author Erwan Daubert
* @version 1.0
*/
public class MavenVersionResolverTest {
@Test
public void testfoundMaxVersion() throws IOException {
MavenResolver resolver = new MavenResolver();
File result = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result.getAbsolutePath());
Assert.assertTrue("RELEASE", !result.getAbsolutePath().contains("SNAPSHOT"));
File result2 = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://repo1.maven.org/maven2"));
System.out.println(result2.getAbsolutePath());
- Assert.assertTrue("RELEASE", !result2.getAbsolutePath().contains("SNAPSHOT") && result2.getAbsolutePath().equals(result.getAbsolutePath()));
+ Assert.assertTrue("RELEASE", !result2.getAbsolutePath().contains("SNAPSHOT"));
File result3 = resolver.resolve("org.kevoree","org.kevoree.core","LATEST","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result3.getCanonicalPath());
Assert.assertTrue("SNAPSHOT", result3.getAbsolutePath().contains("SNAPSHOT"));
/*
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://maven.kevoree.org/release", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());
// local resolution => is it possible ?
/*artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());*/
}
}
| true | true |
public void testfoundMaxVersion() throws IOException {
MavenResolver resolver = new MavenResolver();
File result = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result.getAbsolutePath());
Assert.assertTrue("RELEASE", !result.getAbsolutePath().contains("SNAPSHOT"));
File result2 = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://repo1.maven.org/maven2"));
System.out.println(result2.getAbsolutePath());
Assert.assertTrue("RELEASE", !result2.getAbsolutePath().contains("SNAPSHOT") && result2.getAbsolutePath().equals(result.getAbsolutePath()));
File result3 = resolver.resolve("org.kevoree","org.kevoree.core","LATEST","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result3.getCanonicalPath());
Assert.assertTrue("SNAPSHOT", result3.getAbsolutePath().contains("SNAPSHOT"));
/*
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://maven.kevoree.org/release", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());
// local resolution => is it possible ?
/*artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());*/
}
|
public void testfoundMaxVersion() throws IOException {
MavenResolver resolver = new MavenResolver();
File result = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result.getAbsolutePath());
Assert.assertTrue("RELEASE", !result.getAbsolutePath().contains("SNAPSHOT"));
File result2 = resolver.resolve("org.kevoree","org.kevoree.core","RELEASE","jar", Arrays.asList("http://repo1.maven.org/maven2"));
System.out.println(result2.getAbsolutePath());
Assert.assertTrue("RELEASE", !result2.getAbsolutePath().contains("SNAPSHOT"));
File result3 = resolver.resolve("org.kevoree","org.kevoree.core","LATEST","jar", Arrays.asList("http://oss.sonatype.org/content/groups/public"));
System.out.println(result3.getCanonicalPath());
Assert.assertTrue("SNAPSHOT", result3.getAbsolutePath().contains("SNAPSHOT"));
/*
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://maven.kevoree.org/release", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
// artifact = resolver.foundMaxVersion(artifact, "http://oss.sonatype.org/content/groups/public", false, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());
// local resolution => is it possible ?
/*artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, true);
System.out.println(artifact.getVersion());
Assert.assertEquals(null, artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-ALPHA", artifact.getVersion());
artifact = new MavenArtefact();
artifact.setGroup("org.kevoree");
artifact.setName("org.kevoree.core");
artifact = resolver.foundMaxVersion(artifact, System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository", true, false);
System.out.println(artifact.getVersion());
Assert.assertEquals("2.0.0-SNAPSHOT", artifact.getVersion());*/
}
|
diff --git a/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/Activator.java b/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/Activator.java
index 8759f4626..9e210f660 100644
--- a/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/Activator.java
+++ b/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/Activator.java
@@ -1,160 +1,160 @@
package org.openscada.ae.monitor.dataitem;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.openscada.ae.event.EventProcessor;
import org.openscada.ae.monitor.MonitorService;
import org.openscada.ae.monitor.dataitem.monitor.internal.bit.BooleanAlarmMonitor;
import org.openscada.ae.monitor.dataitem.monitor.internal.bit.MonitorFactoryImpl;
import org.openscada.ae.monitor.dataitem.monitor.internal.level.LevelMonitorFactoryImpl;
import org.openscada.ae.monitor.dataitem.monitor.internal.remote.RemoteAttributeMonitorFactoryImpl;
import org.openscada.ae.monitor.dataitem.monitor.internal.remote.RemoteBooleanAttributeAlarmMonitor;
import org.openscada.ae.monitor.dataitem.monitor.internal.remote.RemoteBooleanValueAlarmMonitor;
import org.openscada.ae.monitor.dataitem.monitor.internal.remote.RemoteValueMonitorFactoryImpl;
import org.openscada.ae.server.common.akn.AknHandler;
import org.openscada.ca.ConfigurationAdministrator;
import org.openscada.ca.ConfigurationFactory;
import org.openscada.da.master.MasterItem;
import org.openscada.utils.concurrent.NamedThreadFactory;
import org.openscada.utils.osgi.pool.ObjectPoolHelper;
import org.openscada.utils.osgi.pool.ObjectPoolImpl;
import org.openscada.utils.osgi.pool.ObjectPoolTracker;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
public class Activator implements BundleActivator
{
private final static Logger logger = Logger.getLogger ( Activator.class );
private static Activator instance;
private EventProcessor eventProcessor;
private ServiceTracker configAdminTracker;
private final Collection<AbstractMonitorFactory> factories = new LinkedList<AbstractMonitorFactory> ();
private ObjectPoolTracker poolTracker;
private ExecutorService executor;
private ObjectPoolImpl monitorServicePool;
private ServiceRegistration monitorServicePoolHandler;
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start ( final BundleContext context ) throws Exception
{
logger.info ( "Starting up..." );
this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
this.eventProcessor = new EventProcessor ( context );
this.eventProcessor.open ();
this.configAdminTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.configAdminTracker.open ();
Dictionary<Object, Object> properties;
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.monitorServicePool = new ObjectPoolImpl ();
this.monitorServicePoolHandler = ObjectPoolHelper.registerObjectPool ( context, this.monitorServicePool, MonitorService.class.getName () );
// monitor service
{
final MonitorFactoryImpl factory = new MonitorFactoryImpl ( context, this.poolTracker, this.monitorServicePool, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, BooleanAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Boolean alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteAttributeMonitorFactoryImpl factory = new RemoteAttributeMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanAttributeAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean attribute alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteValueMonitorFactoryImpl factory = new RemoteValueMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanValueAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean value alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
- makeLevelFactory ( context, "ceil", "MAX", true, true, 2000, true );
- makeLevelFactory ( context, "highhigh", "HH", true, false, 2000, false );
- makeLevelFactory ( context, "high", "H", true, false, 2000, false );
- makeLevelFactory ( context, "low", "L", false, false, 2000, false );
- makeLevelFactory ( context, "lowlow", "LL", false, false, 2000, false );
- makeLevelFactory ( context, "floor", "MIN", false, true, 2000, true );
+ makeLevelFactory ( context, "ceil", "MAX", true, true, 1400, true );
+ makeLevelFactory ( context, "highhigh", "HH", true, false, 1300, false );
+ makeLevelFactory ( context, "high", "H", true, false, 1300, false );
+ makeLevelFactory ( context, "low", "L", false, false, 1300, false );
+ makeLevelFactory ( context, "lowlow", "LL", false, false, 1300, false );
+ makeLevelFactory ( context, "floor", "MIN", false, true, 1400, true );
logger.info ( "Starting up...done" );
Activator.instance = this;
}
private void makeLevelFactory ( final BundleContext context, final String type, final String defaultMonitorType, final boolean lowerOk, final boolean includedOk, final int priority, final boolean cap )
{
Dictionary<Object, Object> properties;
final LevelMonitorFactoryImpl factory = new LevelMonitorFactoryImpl ( context, this.poolTracker, this.monitorServicePool, this.eventProcessor, type, defaultMonitorType, lowerOk, includedOk, priority, cap );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, LevelMonitorFactoryImpl.FACTORY_PREFIX + "." + type );
properties.put ( Constants.SERVICE_DESCRIPTION, type + " Alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop ( final BundleContext context ) throws Exception
{
Activator.instance = null;
// shut down factories
for ( final AbstractMonitorFactory factory : this.factories )
{
factory.dispose ();
}
// shut down object pool
this.monitorServicePoolHandler.unregister ();
this.monitorServicePool.dispose ();
// shut down executor
this.executor.shutdown ();
// shut down event processor
this.eventProcessor.close ();
}
public static ConfigurationAdministrator getConfigAdmin ()
{
return (ConfigurationAdministrator)Activator.instance.configAdminTracker.getService ();
}
}
| true | true |
public void start ( final BundleContext context ) throws Exception
{
logger.info ( "Starting up..." );
this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
this.eventProcessor = new EventProcessor ( context );
this.eventProcessor.open ();
this.configAdminTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.configAdminTracker.open ();
Dictionary<Object, Object> properties;
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.monitorServicePool = new ObjectPoolImpl ();
this.monitorServicePoolHandler = ObjectPoolHelper.registerObjectPool ( context, this.monitorServicePool, MonitorService.class.getName () );
// monitor service
{
final MonitorFactoryImpl factory = new MonitorFactoryImpl ( context, this.poolTracker, this.monitorServicePool, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, BooleanAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Boolean alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteAttributeMonitorFactoryImpl factory = new RemoteAttributeMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanAttributeAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean attribute alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteValueMonitorFactoryImpl factory = new RemoteValueMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanValueAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean value alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
makeLevelFactory ( context, "ceil", "MAX", true, true, 2000, true );
makeLevelFactory ( context, "highhigh", "HH", true, false, 2000, false );
makeLevelFactory ( context, "high", "H", true, false, 2000, false );
makeLevelFactory ( context, "low", "L", false, false, 2000, false );
makeLevelFactory ( context, "lowlow", "LL", false, false, 2000, false );
makeLevelFactory ( context, "floor", "MIN", false, true, 2000, true );
logger.info ( "Starting up...done" );
Activator.instance = this;
}
|
public void start ( final BundleContext context ) throws Exception
{
logger.info ( "Starting up..." );
this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
this.eventProcessor = new EventProcessor ( context );
this.eventProcessor.open ();
this.configAdminTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.configAdminTracker.open ();
Dictionary<Object, Object> properties;
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.monitorServicePool = new ObjectPoolImpl ();
this.monitorServicePoolHandler = ObjectPoolHelper.registerObjectPool ( context, this.monitorServicePool, MonitorService.class.getName () );
// monitor service
{
final MonitorFactoryImpl factory = new MonitorFactoryImpl ( context, this.poolTracker, this.monitorServicePool, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, BooleanAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Boolean alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteAttributeMonitorFactoryImpl factory = new RemoteAttributeMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanAttributeAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean attribute alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
// remote monitor service
{
final RemoteValueMonitorFactoryImpl factory = new RemoteValueMonitorFactoryImpl ( context, this.monitorServicePool, this.executor, this.poolTracker, this.eventProcessor );
properties = new Hashtable<Object, Object> ();
properties.put ( ConfigurationAdministrator.FACTORY_ID, RemoteBooleanValueAlarmMonitor.FACTORY_ID );
properties.put ( Constants.SERVICE_DESCRIPTION, "Remote Boolean value alarms" );
context.registerService ( new String[] { ConfigurationFactory.class.getName (), AknHandler.class.getName () }, factory, properties );
this.factories.add ( factory );
}
makeLevelFactory ( context, "ceil", "MAX", true, true, 1400, true );
makeLevelFactory ( context, "highhigh", "HH", true, false, 1300, false );
makeLevelFactory ( context, "high", "H", true, false, 1300, false );
makeLevelFactory ( context, "low", "L", false, false, 1300, false );
makeLevelFactory ( context, "lowlow", "LL", false, false, 1300, false );
makeLevelFactory ( context, "floor", "MIN", false, true, 1400, true );
logger.info ( "Starting up...done" );
Activator.instance = this;
}
|
diff --git a/farrago/src/net/sf/farrago/namespace/impl/MedAbstractColumnSet.java b/farrago/src/net/sf/farrago/namespace/impl/MedAbstractColumnSet.java
index e8dade8e2..30966e90b 100644
--- a/farrago/src/net/sf/farrago/namespace/impl/MedAbstractColumnSet.java
+++ b/farrago/src/net/sf/farrago/namespace/impl/MedAbstractColumnSet.java
@@ -1,296 +1,296 @@
/*
// $Id$
// Farrago is an extensible data management system.
// Copyright (C) 2005-2005 The Eigenbase Project
// Copyright (C) 2005-2005 Disruptive Tech
// Copyright (C) 2005-2005 LucidEra, Inc.
// Portions Copyright (C) 2003-2005 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sf.farrago.namespace.impl;
import java.util.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.namespace.*;
import net.sf.farrago.query.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.runtime.FarragoUdrRuntime;
import net.sf.farrago.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
import org.eigenbase.sql.*;
/**
* MedAbstractColumnSet is an abstract base class for implementations of the
* {@link FarragoMedColumnSet} interface.
*
* @author John V. Sichi
* @version $Id$
*/
public abstract class MedAbstractColumnSet
extends RelOptAbstractTable
implements FarragoQueryColumnSet
{
//~ Instance fields --------------------------------------------------------
private final String [] localName;
private final String [] foreignName;
private Properties tableProps;
private Map<String, Properties> columnPropMap;
private FarragoPreparingStmt preparingStmt;
private CwmNamedColumnSet cwmColumnSet;
private SqlAccessType allowedAccess;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new MedAbstractColumnSet.
*
* @param localName name of this ColumnSet as it will be known within the
* Farrago system
* @param foreignName name of this ColumnSet as it is known on the foreign
* server; may be null if no meaningful name exists
* @param rowType row type descriptor
* @param tableProps table-level properties
* @param columnPropMap column-level properties (map from column name to
* Properties object)
*/
protected MedAbstractColumnSet(
String [] localName,
String [] foreignName,
RelDataType rowType,
Properties tableProps,
Map<String, Properties> columnPropMap)
{
super(null, localName[localName.length - 1], rowType);
this.localName = localName;
this.foreignName = foreignName;
this.tableProps = tableProps;
this.columnPropMap = columnPropMap;
this.allowedAccess = SqlAccessType.ALL;
}
//~ Methods ----------------------------------------------------------------
// implement RelOptTable
public String [] getQualifiedName()
{
return localName;
}
/**
* @return the name this ColumnSet is known by within the Farrago system
*/
public String [] getLocalName()
{
return localName;
}
/**
* @return the name of this ColumnSet as it is known on the foreign server
*/
public String [] getForeignName()
{
return foreignName;
}
/**
* @return options specified by CREATE FOREIGN TABLE
*/
public Properties getTableProperties()
{
return tableProps;
}
/**
* @return map (from column name to Properties) of column options specified
* by CREATE FOREIGN TABLE
*/
public Map<String, Properties> getColumnPropertyMap()
{
return columnPropMap;
}
// implement FarragoQueryColumnSet
public FarragoPreparingStmt getPreparingStmt()
{
return preparingStmt;
}
// implement FarragoQueryColumnSet
public void setPreparingStmt(FarragoPreparingStmt stmt)
{
preparingStmt = stmt;
}
// implement FarragoQueryColumnSet
public void setCwmColumnSet(CwmNamedColumnSet cwmColumnSet)
{
this.cwmColumnSet = cwmColumnSet;
}
// implement FarragoQueryColumnSet
public CwmNamedColumnSet getCwmColumnSet()
{
return cwmColumnSet;
}
// implement SqlValidatorTable
public boolean isMonotonic(String columnName)
{
return false;
}
// implement SqlValidatorTable
public SqlAccessType getAllowedAccess()
{
return allowedAccess;
}
public void setAllowedAccess(SqlAccessType allowedAccess)
{
this.allowedAccess = allowedAccess;
}
/**
* Provides an implementation of the toRel interface method in terms of an
* underlying UDX.
*
* @param cluster same as for toRel
* @param connection same as for toRel
* @param udxSpecificName specific name with which the UDX was created
* (either via the SPECIFIC keyword or the invocation name if SPECIFIC was
* not specified); this can be a qualified name, possibly with quoted
* identifiers, e.g. x.y.z or x."y".z
* @param serverMofId if not null, the invoked UDX can access the data
* server with the given MOFID at runtime via
* {@link FarragoUdrRuntime#getDataServerRuntimeSupport}
* @param args arguments to UDX invocation
*
* @return generated relational expression producing the UDX results
*/
protected RelNode toUdxRel(
RelOptCluster cluster,
RelOptConnection connection,
String udxSpecificName,
String serverMofId,
RexNode [] args)
{
// TODO jvs 13-Oct-2006: phase out these vestigial parameters
assert(cluster == getPreparingStmt().getRelOptCluster());
assert(connection == getPreparingStmt());
return FarragoJavaUdxRel.newUdxRel(
getPreparingStmt(),
getRowType(),
udxSpecificName,
serverMofId,
args,
RelNode.emptyArray);
}
/**
* Converts one RelNode to another RelNode with specified RowType.
* New columns are filled with nulls.
*
* @param cluster same as for toRel
* @param child original RelNode
* @param targetRowType RowType to map to
* @param srcRowType RowType of external data source
*/
protected RelNode toLenientRel(
RelOptCluster cluster,
RelNode child,
RelDataType targetRowType,
RelDataType srcRowType)
{
ArrayList<RexNode> rexNodeList = new ArrayList();
RexBuilder rexBuilder = cluster.getRexBuilder();
FarragoWarningQueue warningQueue =
getPreparingStmt().getStmtValidator().getWarningQueue();
String objectName = this.localName[this.localName.length-1];
HashMap<String, RelDataType> srcMap = new HashMap();
for (RelDataTypeField srcField : srcRowType.getFieldList()) {
srcMap.put(srcField.getName(), srcField.getType());
}
ArrayList<String> allTargetFields = new ArrayList();
+ int index = 0;
for (RelDataTypeField targetField : targetRowType.getFieldList()) {
- int index = 0;
allTargetFields.add(targetField.getName());
RelDataType type;
if ((type = srcMap.get(targetField.getName())) != null) {
if (type != targetField.getType()) {
// field type cast
warningQueue.postWarning(
FarragoResource.instance().TypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
}
rexNodeList.add(new RexInputRef(index, targetField.getType()));
} else { // field in target not in child
// check if type-incompatibility between source and target
if ((type = srcMap.get(targetField.getName())) != null) {
warningQueue.postWarning(FarragoResource.instance().
IncompatibleTypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
} else {
// field in target has been deleted in source
RelDataType targetType = targetField.getType();
rexNodeList.add(
rexBuilder.makeCast(
targetType,
rexBuilder.constantNull()));
warningQueue.postWarning(
FarragoResource.instance().DeletedFieldWarning.ex(
objectName, targetField.getName()));
}
}
index++;
}
// check if data source has added fields
for (String srcField : srcMap.keySet()) {
if (!allTargetFields.contains(srcField)) {
warningQueue.postWarning(
FarragoResource.instance().AddedFieldWarning.ex(
objectName, srcField));
}
}
// create a new RelNode.
RelNode calcRel = CalcRel.createProject(
child,
rexNodeList,
null);
return RelOptUtil.createCastRel(
calcRel,
targetRowType,
true);
}
}
// End MedAbstractColumnSet.java
| false | true |
protected RelNode toLenientRel(
RelOptCluster cluster,
RelNode child,
RelDataType targetRowType,
RelDataType srcRowType)
{
ArrayList<RexNode> rexNodeList = new ArrayList();
RexBuilder rexBuilder = cluster.getRexBuilder();
FarragoWarningQueue warningQueue =
getPreparingStmt().getStmtValidator().getWarningQueue();
String objectName = this.localName[this.localName.length-1];
HashMap<String, RelDataType> srcMap = new HashMap();
for (RelDataTypeField srcField : srcRowType.getFieldList()) {
srcMap.put(srcField.getName(), srcField.getType());
}
ArrayList<String> allTargetFields = new ArrayList();
for (RelDataTypeField targetField : targetRowType.getFieldList()) {
int index = 0;
allTargetFields.add(targetField.getName());
RelDataType type;
if ((type = srcMap.get(targetField.getName())) != null) {
if (type != targetField.getType()) {
// field type cast
warningQueue.postWarning(
FarragoResource.instance().TypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
}
rexNodeList.add(new RexInputRef(index, targetField.getType()));
} else { // field in target not in child
// check if type-incompatibility between source and target
if ((type = srcMap.get(targetField.getName())) != null) {
warningQueue.postWarning(FarragoResource.instance().
IncompatibleTypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
} else {
// field in target has been deleted in source
RelDataType targetType = targetField.getType();
rexNodeList.add(
rexBuilder.makeCast(
targetType,
rexBuilder.constantNull()));
warningQueue.postWarning(
FarragoResource.instance().DeletedFieldWarning.ex(
objectName, targetField.getName()));
}
}
index++;
}
// check if data source has added fields
for (String srcField : srcMap.keySet()) {
if (!allTargetFields.contains(srcField)) {
warningQueue.postWarning(
FarragoResource.instance().AddedFieldWarning.ex(
objectName, srcField));
}
}
// create a new RelNode.
RelNode calcRel = CalcRel.createProject(
child,
rexNodeList,
null);
return RelOptUtil.createCastRel(
calcRel,
targetRowType,
true);
}
|
protected RelNode toLenientRel(
RelOptCluster cluster,
RelNode child,
RelDataType targetRowType,
RelDataType srcRowType)
{
ArrayList<RexNode> rexNodeList = new ArrayList();
RexBuilder rexBuilder = cluster.getRexBuilder();
FarragoWarningQueue warningQueue =
getPreparingStmt().getStmtValidator().getWarningQueue();
String objectName = this.localName[this.localName.length-1];
HashMap<String, RelDataType> srcMap = new HashMap();
for (RelDataTypeField srcField : srcRowType.getFieldList()) {
srcMap.put(srcField.getName(), srcField.getType());
}
ArrayList<String> allTargetFields = new ArrayList();
int index = 0;
for (RelDataTypeField targetField : targetRowType.getFieldList()) {
allTargetFields.add(targetField.getName());
RelDataType type;
if ((type = srcMap.get(targetField.getName())) != null) {
if (type != targetField.getType()) {
// field type cast
warningQueue.postWarning(
FarragoResource.instance().TypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
}
rexNodeList.add(new RexInputRef(index, targetField.getType()));
} else { // field in target not in child
// check if type-incompatibility between source and target
if ((type = srcMap.get(targetField.getName())) != null) {
warningQueue.postWarning(FarragoResource.instance().
IncompatibleTypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
} else {
// field in target has been deleted in source
RelDataType targetType = targetField.getType();
rexNodeList.add(
rexBuilder.makeCast(
targetType,
rexBuilder.constantNull()));
warningQueue.postWarning(
FarragoResource.instance().DeletedFieldWarning.ex(
objectName, targetField.getName()));
}
}
index++;
}
// check if data source has added fields
for (String srcField : srcMap.keySet()) {
if (!allTargetFields.contains(srcField)) {
warningQueue.postWarning(
FarragoResource.instance().AddedFieldWarning.ex(
objectName, srcField));
}
}
// create a new RelNode.
RelNode calcRel = CalcRel.createProject(
child,
rexNodeList,
null);
return RelOptUtil.createCastRel(
calcRel,
targetRowType,
true);
}
|
diff --git a/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java b/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java
index 5cb13b3..9d6942b 100644
--- a/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java
+++ b/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java
@@ -1,298 +1,298 @@
package com.github.mineguild.MineguildAdmin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class MGACommandExecutor implements CommandExecutor {
public MGACommandExecutor(Main plugin) {
}
@SuppressWarnings({ "unused"})
@Override
//Command interpreter
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
//Introducing /mga command
if(cmd.getName().equalsIgnoreCase("mga")){
//If the args are length 0 or the args[0] isnt equal "version" it will return false
if (args.length == 0 || !args[0].equalsIgnoreCase("version")){
return false;
}
if (args[0].equalsIgnoreCase("version")) {
//Show version to sender and return true if the value of args[0] is equal to "version"
sender.sendMessage("MineguildAdmin V0.3");
return true;
}
}
//Introducing /heal command
if(cmd.getName().equalsIgnoreCase("heal")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max Health and message
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
String pname = p.getName();
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
sender.sendMessage(ChatColor.RED+"You just healed " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /feed command
if(cmd.getName().equalsIgnoreCase("feed")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max hunger level and message
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You feeded yourself");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max hunger level and message both
String pname = p.getName();
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You were feeded.");
sender.sendMessage(ChatColor.RED+"You just feeded " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /check command
if(cmd.getName().equalsIgnoreCase("check")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//check health then /2 and print
double health = p.getHealth();
health = health / 2.0;
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
p.sendMessage(ChatColor.RED+"Your Health is " + health);
p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger);
return true;
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
double health = p.getHealth();
String string1 = p.getName();
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
health = health / 2.0;
sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health);
sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /gm command
if(cmd.getName().equalsIgnoreCase("gm")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
else if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){
if(sender instanceof Player){
Player p = (Player) sender;
if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
else{
- if(sender instanceof Player){
- Player p = Bukkit.getPlayerExact(args[0]);
- String pname = p.getDisplayName();
+ if(sender instanceof Player){
//If the above defined player isn�t null continue
+ Player p = Bukkit.getPlayerExact(args[0]);
if(p != null){
+ String pname = p.getDisplayName();
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
else if (args.length == 2) {
if(sender instanceof Player){
Player p = Bukkit.getPlayerExact(args[0]);
String pname = p.getDisplayName();
if(p != null){
if (args[1].equalsIgnoreCase("c") || args[1].equals("1")){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
return true;
}
if(args[1].equalsIgnoreCase("s") || args[1].equals("0")){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
if(cmd.getName().equalsIgnoreCase("spawn")){
if(args.length == 0){
if(sender instanceof Player){
Player p = (Player) sender;
Location l = p.getWorld().getSpawnLocation();
p.teleport(l);
sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!");
return true;
}
}
else{
return false;
}
}
if(cmd.getName().equalsIgnoreCase("setspawn")){
if(sender instanceof Player){
Player p = (Player) sender;
int x = p.getLocation().getBlockX();
int y = p.getLocation().getBlockY();
int z = p.getLocation().getBlockZ();
p.getWorld().setSpawnLocation(x, y, z);
sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You only can use this command as player!");
return true;
}
}
return false;
}
}
| false | true |
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
//Introducing /mga command
if(cmd.getName().equalsIgnoreCase("mga")){
//If the args are length 0 or the args[0] isnt equal "version" it will return false
if (args.length == 0 || !args[0].equalsIgnoreCase("version")){
return false;
}
if (args[0].equalsIgnoreCase("version")) {
//Show version to sender and return true if the value of args[0] is equal to "version"
sender.sendMessage("MineguildAdmin V0.3");
return true;
}
}
//Introducing /heal command
if(cmd.getName().equalsIgnoreCase("heal")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max Health and message
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
String pname = p.getName();
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
sender.sendMessage(ChatColor.RED+"You just healed " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /feed command
if(cmd.getName().equalsIgnoreCase("feed")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max hunger level and message
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You feeded yourself");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max hunger level and message both
String pname = p.getName();
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You were feeded.");
sender.sendMessage(ChatColor.RED+"You just feeded " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /check command
if(cmd.getName().equalsIgnoreCase("check")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//check health then /2 and print
double health = p.getHealth();
health = health / 2.0;
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
p.sendMessage(ChatColor.RED+"Your Health is " + health);
p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger);
return true;
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
double health = p.getHealth();
String string1 = p.getName();
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
health = health / 2.0;
sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health);
sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /gm command
if(cmd.getName().equalsIgnoreCase("gm")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
else if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){
if(sender instanceof Player){
Player p = (Player) sender;
if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
else{
if(sender instanceof Player){
Player p = Bukkit.getPlayerExact(args[0]);
String pname = p.getDisplayName();
//If the above defined player isn�t null continue
if(p != null){
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
else if (args.length == 2) {
if(sender instanceof Player){
Player p = Bukkit.getPlayerExact(args[0]);
String pname = p.getDisplayName();
if(p != null){
if (args[1].equalsIgnoreCase("c") || args[1].equals("1")){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
return true;
}
if(args[1].equalsIgnoreCase("s") || args[1].equals("0")){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
if(cmd.getName().equalsIgnoreCase("spawn")){
if(args.length == 0){
if(sender instanceof Player){
Player p = (Player) sender;
Location l = p.getWorld().getSpawnLocation();
p.teleport(l);
sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!");
return true;
}
}
else{
return false;
}
}
if(cmd.getName().equalsIgnoreCase("setspawn")){
if(sender instanceof Player){
Player p = (Player) sender;
int x = p.getLocation().getBlockX();
int y = p.getLocation().getBlockY();
int z = p.getLocation().getBlockZ();
p.getWorld().setSpawnLocation(x, y, z);
sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You only can use this command as player!");
return true;
}
}
return false;
}
|
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
//Introducing /mga command
if(cmd.getName().equalsIgnoreCase("mga")){
//If the args are length 0 or the args[0] isnt equal "version" it will return false
if (args.length == 0 || !args[0].equalsIgnoreCase("version")){
return false;
}
if (args[0].equalsIgnoreCase("version")) {
//Show version to sender and return true if the value of args[0] is equal to "version"
sender.sendMessage("MineguildAdmin V0.3");
return true;
}
}
//Introducing /heal command
if(cmd.getName().equalsIgnoreCase("heal")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max Health and message
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
String pname = p.getName();
p.setHealth(20);
p.sendMessage(ChatColor.RED+"You feel restored");
sender.sendMessage(ChatColor.RED+"You just healed " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /feed command
if(cmd.getName().equalsIgnoreCase("feed")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//set max hunger level and message
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You feeded yourself");
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!");
return true;
}
}
//If the args have the length 1 continue
else {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max hunger level and message both
String pname = p.getName();
p.setFoodLevel(20);
p.sendMessage(ChatColor.RED+"You were feeded.");
sender.sendMessage(ChatColor.RED+"You just feeded " + pname);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /check command
if(cmd.getName().equalsIgnoreCase("check")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//check health then /2 and print
double health = p.getHealth();
health = health / 2.0;
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
p.sendMessage(ChatColor.RED+"Your Health is " + health);
p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger);
return true;
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
Player p = Bukkit.getPlayerExact(args[0]);
//If the above defined player isn�t null continue
if(p != null){
//set max Health and message
double health = p.getHealth();
String string1 = p.getName();
double hunger = p.getFoodLevel();
hunger = hunger / 2.0;
health = health / 2.0;
sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health);
sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger);
return true;
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else {
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
}
//Introducing /gm command
if(cmd.getName().equalsIgnoreCase("gm")){
//If there are no args, simply act with the command sender
if(args.length == 0){
//Only do this if the sender is instanceof player
if(sender instanceof Player){
Player p = (Player) sender;
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
else if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If the sender is not instanceof player send message with console use back to the sender
else {
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
//If the args have the length 1 continue
if(args.length == 1) {
if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){
if(sender instanceof Player){
Player p = (Player) sender;
if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
else{
if(sender instanceof Player){
//If the above defined player isn�t null continue
Player p = Bukkit.getPlayerExact(args[0]);
if(p != null){
String pname = p.getDisplayName();
//If the gamemode is survival it will switch to creative and vice versa
//Also returning true, for the correctness
if (p.getGameMode().equals(GameMode.SURVIVAL)){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
p.sendMessage(ChatColor.GOLD + "You are now in creative mode!");
return true;
}
if (p.getGameMode().equals(GameMode.CREATIVE)){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
p.sendMessage(ChatColor.GOLD + "You are now in survival mode!");
return true;
}
}
//If output of Bukkit.getPlayerExact(args[0] was null, send error message.
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
else if (args.length == 2) {
if(sender instanceof Player){
Player p = Bukkit.getPlayerExact(args[0]);
String pname = p.getDisplayName();
if(p != null){
if (args[1].equalsIgnoreCase("c") || args[1].equals("1")){
p.setGameMode(GameMode.CREATIVE);
sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!");
return true;
}
if(args[1].equalsIgnoreCase("s") || args[1].equals("0")){
p.setGameMode(GameMode.SURVIVAL);
sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Player is not online!");
return true;
}
}
else{
sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!");
return true;
}
}
}
if(cmd.getName().equalsIgnoreCase("spawn")){
if(args.length == 0){
if(sender instanceof Player){
Player p = (Player) sender;
Location l = p.getWorld().getSpawnLocation();
p.teleport(l);
sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!");
return true;
}
}
else{
return false;
}
}
if(cmd.getName().equalsIgnoreCase("setspawn")){
if(sender instanceof Player){
Player p = (Player) sender;
int x = p.getLocation().getBlockX();
int y = p.getLocation().getBlockY();
int z = p.getLocation().getBlockZ();
p.getWorld().setSpawnLocation(x, y, z);
sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location");
return true;
}
else{
sender.sendMessage(ChatColor.RED + "You only can use this command as player!");
return true;
}
}
return false;
}
|
diff --git a/FlexAscParser/src_converter/Main2.java b/FlexAscParser/src_converter/Main2.java
index 7260fd6..21981df 100644
--- a/FlexAscParser/src_converter/Main2.java
+++ b/FlexAscParser/src_converter/Main2.java
@@ -1,2332 +1,2333 @@
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import macromedia.asc.parser.ApplyTypeExprNode;
import macromedia.asc.parser.ArgumentListNode;
import macromedia.asc.parser.BinaryExpressionNode;
import macromedia.asc.parser.BreakStatementNode;
import macromedia.asc.parser.CallExpressionNode;
import macromedia.asc.parser.CaseLabelNode;
import macromedia.asc.parser.ClassDefinitionNode;
import macromedia.asc.parser.CoerceNode;
import macromedia.asc.parser.ConditionalExpressionNode;
import macromedia.asc.parser.DeleteExpressionNode;
import macromedia.asc.parser.DoStatementNode;
import macromedia.asc.parser.ExpressionStatementNode;
import macromedia.asc.parser.ForStatementNode;
import macromedia.asc.parser.FunctionCommonNode;
import macromedia.asc.parser.FunctionDefinitionNode;
import macromedia.asc.parser.FunctionNameNode;
import macromedia.asc.parser.GetExpressionNode;
import macromedia.asc.parser.HasNextNode;
import macromedia.asc.parser.IdentifierNode;
import macromedia.asc.parser.IfStatementNode;
import macromedia.asc.parser.ImportDirectiveNode;
import macromedia.asc.parser.IncrementNode;
import macromedia.asc.parser.InterfaceDefinitionNode;
import macromedia.asc.parser.ListNode;
import macromedia.asc.parser.LiteralArrayNode;
import macromedia.asc.parser.LiteralBooleanNode;
import macromedia.asc.parser.LiteralNullNode;
import macromedia.asc.parser.LiteralNumberNode;
import macromedia.asc.parser.LiteralObjectNode;
import macromedia.asc.parser.LiteralRegExpNode;
import macromedia.asc.parser.LiteralStringNode;
import macromedia.asc.parser.MemberExpressionNode;
import macromedia.asc.parser.MetaDataNode;
import macromedia.asc.parser.Node;
import macromedia.asc.parser.PackageDefinitionNode;
import macromedia.asc.parser.ParameterListNode;
import macromedia.asc.parser.ParameterNode;
import macromedia.asc.parser.Parser;
import macromedia.asc.parser.ProgramNode;
import macromedia.asc.parser.QualifiedIdentifierNode;
import macromedia.asc.parser.ReturnStatementNode;
import macromedia.asc.parser.SelectorNode;
import macromedia.asc.parser.SetExpressionNode;
import macromedia.asc.parser.StatementListNode;
import macromedia.asc.parser.StoreRegisterNode;
import macromedia.asc.parser.SuperExpressionNode;
import macromedia.asc.parser.SuperStatementNode;
import macromedia.asc.parser.SwitchStatementNode;
import macromedia.asc.parser.ThisExpressionNode;
import macromedia.asc.parser.ThrowStatementNode;
import macromedia.asc.parser.Tokens;
import macromedia.asc.parser.TryStatementNode;
import macromedia.asc.parser.UnaryExpressionNode;
import macromedia.asc.parser.VariableBindingNode;
import macromedia.asc.parser.VariableDefinitionNode;
import macromedia.asc.parser.WhileStatementNode;
import macromedia.asc.util.Context;
import macromedia.asc.util.ContextStatics;
import macromedia.asc.util.ObjectList;
import bc.builtin.BuiltinClasses;
import bc.code.FileWriteDestination;
import bc.code.ListWriteDestination;
import bc.code.WriteDestination;
import bc.help.BcCodeCs;
import bc.help.BcNodeHelper;
import bc.lang.BcClassDefinitionNode;
import bc.lang.BcFuncParam;
import bc.lang.BcFunctionDeclaration;
import bc.lang.BcFunctionTypeNode;
import bc.lang.BcInterfaceDefinitionNode;
import bc.lang.BcMemberExpressionNode;
import bc.lang.BcTypeNode;
import bc.lang.BcVariableDeclaration;
import bc.lang.BcVectorTypeNode;
public class Main2
{
private static FileWriteDestination src;
private static ListWriteDestination impl;
private static WriteDestination dest;
private static Stack<WriteDestination> destStack;
private static BcClassDefinitionNode lastBcClass;
private static BcFunctionDeclaration lastBcFunction;
private static BcTypeNode lastBcMemberType;
private static final String classObject = "Object";
private static final String classString = "String";
private static final String classVector = "Vector";
private static final String classDictionary = "Dictionary";
private static final String classXML = "XML";
private static final String classXMLList = "XMLList";
private static List<BcVariableDeclaration> declaredVars;
private static List<BcClassDefinitionNode> bcClasses;
private static Map<String, BcClassDefinitionNode> builtinClasses; // builtin classes
private static Map<String, BcFunctionDeclaration> bcBuitinFunctions; // top level functions
// FIXME: filter class names
private static String[] builtinClassesNames =
{
"Object",
"Array",
"Dictionary",
"Sprite",
"Rectangle",
"Stage",
"Event",
"MouseEvent",
"KeyboardEvent",
"DisplayObject",
"DisplayObjectContainer",
"MovieClip",
"TextField",
"TextFormat",
"DropShadowFilter",
"Bitmap",
"Sound",
"SoundTransform",
"SoundChannel",
"ColorTransform",
"BitmapData",
"ByteArray",
"Class",
"RegExp",
"URLRequest",
"Loader",
"URLLoader",
"IOErrorEvent",
"*",
"SharedObject",
"Shape",
"Graphics",
"BlurFilter",
"Point",
"Math",
"StageAlign",
"StageScaleMode",
"StageQuality",
"StageDisplayState",
"PixelSnapping",
"TextFieldAutoSize",
"Mouse",
"Keyboard",
};
static
{
builtinClasses = new HashMap<String, BcClassDefinitionNode>();
bcBuitinFunctions = new HashMap<String, BcFunctionDeclaration>();
for (String className : builtinClassesNames)
{
builtinClasses.put(className, new BcClassDefinitionNode(BcTypeNode.create(className)));
}
try
{
List<BcClassDefinitionNode> classes = BuiltinClasses.load(new File("as_classes"));
for (BcClassDefinitionNode bcClass : classes)
{
if (bcClass.getName().equals(BuiltinClasses.TOPLEVEL_DUMMY_CLASS_NAME))
{
List<BcFunctionDeclaration> bcTopLevelFunctions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : bcTopLevelFunctions)
{
bcBuitinFunctions.put(bcFunc.getName(), bcFunc);
}
}
else
{
builtinClasses.put(bcClass.getName(), bcClass);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
File outputDir = new File(args[0]);
String[] filenames = new String[args.length - 1];
System.arraycopy(args, 1, filenames, 0, filenames.length);
try
{
collect(filenames);
process();
write(outputDir);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static void collect(String[] filenames) throws IOException
{
bcClasses = new ArrayList<BcClassDefinitionNode>();
for (int i = 0; i < filenames.length; ++i)
{
collect(new File(filenames[i]));
}
}
private static void collect(File file) throws IOException
{
if (file.isDirectory())
{
File[] files = file.listFiles(new FileFilter()
{
@Override
public boolean accept(File pathname)
{
String filename = pathname.getName();
if (pathname.isDirectory())
return !filename.equals(".svn");
return filename.endsWith(".as");
}
});
for (File child : files)
{
collect(child);
}
}
else
{
collectSource(file);
}
}
private static void collectSource(File file) throws IOException
{
ContextStatics statics = new ContextStatics();
Context cx = new Context(statics);
FileInputStream in = new FileInputStream(file);
Parser parser = new Parser(cx, in, file.getPath());
ProgramNode programNode = parser.parseProgram();
in.close();
// NodePrinter printer = new NodePrinter();
// printer.evaluate(cx, programNode);
for (Node node : programNode.statements.items)
{
dest = new ListWriteDestination();
destStack = new Stack<WriteDestination>();
if (node instanceof InterfaceDefinitionNode)
{
BcInterfaceDefinitionNode bcInterface = collect((InterfaceDefinitionNode) node);
bcClasses.add(bcInterface);
}
else if (node instanceof ClassDefinitionNode)
{
BcClassDefinitionNode bcClass = collect((ClassDefinitionNode) node);
bcClasses.add(bcClass);
}
else if (node instanceof ImportDirectiveNode ||
node instanceof PackageDefinitionNode ||
node instanceof MetaDataNode)
{
// nothing
}
}
}
private static BcInterfaceDefinitionNode collect(InterfaceDefinitionNode interfaceDefinitionNode)
{
String interfaceDeclaredName = interfaceDefinitionNode.name.name;
declaredVars = new ArrayList<BcVariableDeclaration>();
BcTypeNode interfaceType = BcTypeNode.create(interfaceDeclaredName);
BcInterfaceDefinitionNode bcInterface = new BcInterfaceDefinitionNode(interfaceType);
bcInterface.setDeclaredVars(declaredVars);
lastBcClass = bcInterface;
ObjectList<Node> items = interfaceDefinitionNode.statements.items;
// collect the stuff
for (Node node : items)
{
if (node instanceof FunctionDefinitionNode)
{
bcInterface.add(collect((FunctionDefinitionNode) node));
}
else
{
assert false;
}
}
lastBcClass = null;
return bcInterface;
}
private static BcClassDefinitionNode collect(ClassDefinitionNode classDefinitionNode)
{
String classDeclaredName = classDefinitionNode.name.name;
declaredVars = new ArrayList<BcVariableDeclaration>();
BcTypeNode classType = BcTypeNode.create(classDeclaredName);
BcClassDefinitionNode bcClass = new BcClassDefinitionNode(classType);
bcClass.setDeclaredVars(declaredVars);
lastBcClass = bcClass;
// super type
Node baseclass = classDefinitionNode.baseclass;
if (baseclass != null)
{
BcTypeNode bcSuperType = extractBcType(baseclass);
bcClass.setExtendsType(bcSuperType);
}
// interfaces
if (classDefinitionNode.interfaces != null)
{
for (Node interfaceNode : classDefinitionNode.interfaces.items)
{
BcTypeNode interfaceType = extractBcType(interfaceNode);
bcClass.addInterface(interfaceType);
}
}
// collect members
ObjectList<Node> items = classDefinitionNode.statements.items;
for (Node node : items)
{
if (node instanceof FunctionDefinitionNode)
{
bcClass.add(collect((FunctionDefinitionNode) node));
}
else if (node instanceof VariableDefinitionNode)
{
bcClass.add(collect((VariableDefinitionNode)node));
}
else if (node instanceof MetaDataNode)
{
}
else if (node instanceof ExpressionStatementNode)
{
assert false : "Top level ExpressionStatementNode";
}
else
{
assert false : node.getClass();
}
}
lastBcClass = null;
declaredVars = null;
return bcClass;
}
private static BcVariableDeclaration collect(VariableDefinitionNode node)
{
assert node.list.items.size() == 1 : node.list.items.size();
VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0);
BcTypeNode bcType = extractBcType(varBindNode.variable.type);
String bcIdentifier = BcNodeHelper.extractBcIdentifier(varBindNode.variable.identifier);
BcVariableDeclaration bcVar = new BcVariableDeclaration(bcType, bcIdentifier);
bcVar.setConst(node.kind == Tokens.CONST_TOKEN);
bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs));
bcVar.setInitializerNode(varBindNode.initializer);
declaredVars.add(bcVar);
return bcVar;
}
private static BcFunctionDeclaration collect(FunctionDefinitionNode functionDefinitionNode)
{
FunctionNameNode functionNameNode = functionDefinitionNode.name;
String name = functionNameNode.identifier.name;
BcFunctionDeclaration bcFunc = new BcFunctionDeclaration(name);
if (functionNameNode.kind == Tokens.GET_TOKEN)
{
bcFunc.setGetter();
}
else if(functionNameNode.kind == Tokens.SET_TOKEN)
{
bcFunc.setSetter();
}
boolean isConstructor = lastBcClass != null && name.equals(lastBcClass.getName());
bcFunc.setConstructorFlag(isConstructor);
bcFunc.setModifiers(BcNodeHelper.extractModifiers(functionDefinitionNode.attrs));
ArrayList<BcVariableDeclaration> declaredVars = new ArrayList<BcVariableDeclaration>();
bcFunc.setDeclaredVars(declaredVars);
// get function params
ParameterListNode parameterNode = functionDefinitionNode.fexpr.signature.parameter;
if (parameterNode != null)
{
ObjectList<ParameterNode> params = parameterNode.items;
for (ParameterNode param : params)
{
BcFuncParam bcParam = new BcFuncParam(extractBcType(param.type), param.identifier.name);
if (param.init != null)
{
bcParam.setDefaultInitializer(param.init);
}
bcFunc.addParam(bcParam);
declaredVars.add(bcParam);
}
}
// get function return type
Node returnTypeNode = functionDefinitionNode.fexpr.signature.result;
if (returnTypeNode != null)
{
BcTypeNode bcReturnType = extractBcType(returnTypeNode);
bcFunc.setReturnType(bcReturnType);
}
bcFunc.setStatements(functionDefinitionNode.fexpr.body);
return bcFunc;
}
private static void process()
{
Collection<BcTypeNode> values = BcTypeNode.uniqueTypes.values();
for (BcTypeNode type : values)
{
process(type);
}
for (BcClassDefinitionNode bcClass : bcClasses)
{
if (bcClass.isInterface())
{
process((BcInterfaceDefinitionNode)bcClass);
}
else
{
process(bcClass);
}
}
}
private static void process(BcInterfaceDefinitionNode bcInterface)
{
List<BcVariableDeclaration> oldDeclaredVars = declaredVars;
declaredVars = bcInterface.getDeclaredVars();
}
private static void process(BcClassDefinitionNode bcClass)
{
System.out.println("Process: " + bcClass.getName());
declaredVars = bcClass.getDeclaredVars();
lastBcClass = bcClass;
List<BcVariableDeclaration> fields = bcClass.getFields();
for (BcVariableDeclaration bcField : fields)
{
process(bcField);
}
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
process(bcFunc);
}
lastBcClass = null;
declaredVars = null;
}
private static void process(BcVariableDeclaration bcVar)
{
BcTypeNode varType = bcVar.getType();
String varId = bcVar.getIdentifier();
dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(varId));
Node initializer = bcVar.getInitializerNode();
if (initializer != null)
{
ListWriteDestination initializerDest = new ListWriteDestination();
pushDest(initializerDest);
process(initializer);
popDest();
bcVar.setInitializer(initializerDest);
bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(initializer));
dest.write(" = " + initializerDest);
}
dest.writeln(";");
}
private static void process(Node node)
{
assert node != null;
if (node instanceof MemberExpressionNode)
process((MemberExpressionNode)node);
else if (node instanceof SelectorNode)
process((SelectorNode)node);
else if (node instanceof IdentifierNode)
process((IdentifierNode)node);
else if (node instanceof ExpressionStatementNode)
process((ExpressionStatementNode)node);
else if (node instanceof VariableBindingNode)
process((VariableBindingNode)node);
else if (node instanceof VariableDefinitionNode)
process((VariableDefinitionNode)node);
else if (node instanceof LiteralNumberNode ||
node instanceof LiteralBooleanNode ||
node instanceof LiteralNullNode ||
node instanceof LiteralObjectNode ||
node instanceof LiteralStringNode ||
node instanceof LiteralRegExpNode ||
node instanceof LiteralArrayNode)
processLiteral(node);
else if (node instanceof BinaryExpressionNode)
process((BinaryExpressionNode)node);
else if (node instanceof UnaryExpressionNode)
process((UnaryExpressionNode)node);
else if (node instanceof IfStatementNode)
process((IfStatementNode)node);
else if (node instanceof ConditionalExpressionNode)
process((ConditionalExpressionNode)node);
else if (node instanceof WhileStatementNode)
process((WhileStatementNode)node);
else if (node instanceof ForStatementNode)
process((ForStatementNode)node);
else if (node instanceof DoStatementNode)
process((DoStatementNode)node);
else if (node instanceof SwitchStatementNode)
process((SwitchStatementNode)node);
else if (node instanceof TryStatementNode)
process((TryStatementNode)node);
else if (node instanceof ReturnStatementNode)
process((ReturnStatementNode)node);
else if (node instanceof BreakStatementNode)
process((BreakStatementNode)node);
else if (node instanceof ThisExpressionNode)
process((ThisExpressionNode)node);
else if (node instanceof SuperExpressionNode)
process((SuperExpressionNode)node);
else if (node instanceof ThrowStatementNode)
process((ThrowStatementNode)node);
else if (node instanceof SuperStatementNode)
process((SuperStatementNode)node);
else if (node instanceof ListNode)
process((ListNode)node);
else if (node instanceof StatementListNode)
process((StatementListNode)node);
else if (node instanceof ArgumentListNode)
process((ArgumentListNode)node);
else if (node instanceof FunctionCommonNode)
process((FunctionCommonNode)node);
else
assert false : node.getClass();
}
private static void process(StatementListNode statementsNode)
{
writeBlockOpen(dest);
ObjectList<Node> items = statementsNode.items;
for (Node node : items)
{
process(node);
}
writeBlockClose(dest);
}
private static void process(ArgumentListNode node)
{
int itemIndex = 0;
for (Node arg : node.items)
{
process(arg);
if (++itemIndex < node.items.size())
{
dest.write(", ");
}
}
}
private static void process(FunctionCommonNode node)
{
System.err.println("Fix me!!! FunctionCommonNode");
}
private static BcVariableDeclaration process(VariableDefinitionNode node)
{
VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0);
BcTypeNode varType = extractBcType(varBindNode.variable.type);
String bcIdentifier = BcNodeHelper.extractBcIdentifier(varBindNode.variable.identifier);
BcVariableDeclaration bcVar = new BcVariableDeclaration(varType, bcIdentifier);
bcVar.setConst(node.kind == Tokens.CONST_TOKEN);
bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs));
dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(bcIdentifier));
if (varBindNode.initializer != null)
{
ListWriteDestination initializer = new ListWriteDestination();
pushDest(initializer);
process(varBindNode.initializer);
popDest();
bcVar.setInitializer(initializer);
bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(varBindNode.initializer));
dest.write(" = " + initializer);
}
dest.writeln(";");
declaredVars.add(bcVar);
return bcVar;
}
// dirty hack: we need to check the recursion depth
private static MemberExpressionNode rootMemberNode;
private static void process(MemberExpressionNode node)
{
lastBcMemberType = null;
String baseIdentifier = null;
Node base = node.base;
SelectorNode selector = node.selector;
if (rootMemberNode == null)
{
rootMemberNode = node;
}
if (base != null)
{
process(base);
boolean staticCall = false;
if (base instanceof MemberExpressionNode)
{
baseIdentifier = BcNodeHelper.tryExtractIdentifier((MemberExpressionNode)base);
if (baseIdentifier != null)
{
staticCall = BcCodeCs.canBeClass(baseIdentifier);
BcTypeNode baseType = findIdentifierType(baseIdentifier);
if (baseType != null)
{
lastBcMemberType = baseType;
}
}
}
else if (base instanceof ThisExpressionNode)
{
lastBcMemberType = lastBcClass.getClassType();
}
else if (base instanceof SuperExpressionNode)
{
lastBcMemberType = lastBcClass.getExtendsType();
}
else if (base instanceof ListNode)
{
ListNode list = (ListNode) base;
assert list.items.size() == 1 : list.items.size();
Node item = list.items.get(0);
if (item instanceof MemberExpressionNode)
{
MemberExpressionNode member = (MemberExpressionNode) item;
assert member.base == null : member.base.getClass();
assert member.selector instanceof CallExpressionNode : member.selector.getClass();
CallExpressionNode call = (CallExpressionNode) member.selector;
assert call.expr instanceof IdentifierNode : call.expr.getClass();
IdentifierNode identifier = (IdentifierNode) call.expr;
BcClassDefinitionNode castClass = findClass(identifier.name);
assert castClass != null : identifier.name;
lastBcMemberType = castClass.getClassType();
}
}
else
{
assert false;
}
if (selector instanceof GetExpressionNode ||
selector instanceof CallExpressionNode ||
selector instanceof SetExpressionNode)
{
if (selector.getMode() == Tokens.DOT_TOKEN)
{
dest.write(staticCall ? "::" : "->");
}
else
{
dest.write("->");
}
}
}
if (selector != null)
{
process(selector);
}
rootMemberNode = null;
}
private static void process(SelectorNode node)
{
if (node instanceof DeleteExpressionNode)
process((DeleteExpressionNode)node);
else if (node instanceof GetExpressionNode)
process((GetExpressionNode)node);
else if (node instanceof CallExpressionNode)
process((CallExpressionNode)node);
else if (node instanceof SetExpressionNode)
process((SetExpressionNode)node);
else if (node instanceof ApplyTypeExprNode)
process((ApplyTypeExprNode)node);
else if (node instanceof IncrementNode)
process((IncrementNode)node);
else
assert false : node.getClass();
}
private static void process(DeleteExpressionNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
assert node.getMode() == Tokens.LEFTBRACKET_TOKEN;
dest.writef("->remove(%s)", expr);
}
private static void process(GetExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String expr = exprDest.toString();
if (lastBcMemberType != null)
{
BcTypeNode memberType = lastBcMemberType;
lastBcMemberType = null;
if (node.expr instanceof IdentifierNode)
{
String identifier = expr;
BcClassDefinitionNode bcClass = memberType.getClassNode();
if (bcClass != null)
{
BcFunctionDeclaration bcFunc = bcClass.findGetterFunction(identifier);
if (bcFunc != null)
{
BcTypeNode funcType = bcFunc.getReturnType();
assert funcType != null : identifier;
expr = identifier + "()";
lastBcMemberType = funcType;
}
else
{
BcVariableDeclaration bcField = bcClass.findField(identifier);
if (bcField != null)
{
BcTypeNode fieldType = bcField.getType();
lastBcMemberType = fieldType;
}
}
}
}
}
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
ListWriteDestination argsDest = new ListWriteDestination();
pushDest(argsDest);
process(node.expr);
popDest();
dest.writef("%s[%s]", expr, argsDest);
}
else
{
dest.write(expr);
}
}
private static BcTypeNode findIdentifierType(String name)
{
if (BcCodeCs.canBeClass(name))
{
BcClassDefinitionNode bcClass = findClass(name);
if (bcClass != null)
{
return bcClass.getClassType();
}
}
BcVariableDeclaration bcVar = findVariable(name);
if (bcVar != null)
{
return bcVar.getType();
}
BcFunctionDeclaration bcFunc = findFunction(name);
if (bcFunc != null)
{
return bcFunc.getReturnType();
}
return null;
}
private static BcVariableDeclaration findVariable(String name)
{
BcVariableDeclaration bcVar = findLocalVar(name);
if (bcVar != null)
{
return bcVar;
}
return lastBcClass.findField(name);
}
private static BcVariableDeclaration findLocalVar(String name)
{
if (lastBcFunction == null)
{
return null;
}
return lastBcFunction.findVariable(name);
}
private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String expr = exprDest.toString();
if (lastBcMemberType != null)
{
BcTypeNode memberType = lastBcMemberType;
lastBcMemberType = null;
if (node.expr instanceof IdentifierNode)
{
String identifier = expr;
BcClassDefinitionNode bcClass = memberType.getClassNode();
if (bcClass != null)
{
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
}
}
}
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
- initDest.write(" << ");
+ initDest.write(".add(");
process(elementNode);
+ initDest.write(")");
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(" << ");
process(elementNode);
}
popDest();
dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest);
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (BcCodeCs.canBeClass(type) || BcCodeCs.isBasicType(type))
{
dest.writef("((%s)(%s))", BcCodeCs.type(exprDest.toString()), argsDest);
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
}
private static void process(SetExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String expr = exprDest.toString();
boolean setterCalled = false;
if (lastBcMemberType != null)
{
BcTypeNode memberType = lastBcMemberType;
lastBcMemberType = null;
if (node.expr instanceof IdentifierNode)
{
String identifier = expr;
BcClassDefinitionNode bcClass = memberType.getClassNode();
if (bcClass != null)
{
BcFunctionDeclaration bcFunc = bcClass.findSetterFunction(identifier);
if (bcFunc != null)
{
List<BcFuncParam> funcParams = bcFunc.getParams();
BcTypeNode setterType = funcParams.get(0).getType();
setterCalled = true;
lastBcMemberType = setterType;
}
}
}
}
ListWriteDestination argsDest = new ListWriteDestination();
pushDest(argsDest);
process(node.args);
popDest();
if (setterCalled)
{
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
dest.writef("[%s](%s)", exprDest, argsDest);
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
else
{
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
dest.writef("[%s] = %s", exprDest, argsDest);
}
else
{
dest.writef("%s = %s", exprDest, argsDest);
}
}
}
private static void process(ApplyTypeExprNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
String typeName = ((IdentifierNode)node.expr).name;
StringBuilder typeBuffer = new StringBuilder(typeName);
ListNode typeArgs = node.typeArgs;
int genericCount = typeArgs.items.size();
if (genericCount > 0)
{
typeBuffer.append("<");
int genericIndex = 0;
for (Node genericTypeNode : typeArgs.items)
{
BcTypeNode genericType = extractBcType(genericTypeNode);
typeBuffer.append(BcCodeCs.type(genericType));
if (++genericIndex < genericCount)
{
typeBuffer.append(",");
}
}
typeBuffer.append(">");
}
String type = typeBuffer.toString();
dest.write(type);
}
private static void process(IncrementNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
String op = Tokens.tokenToString[-node.op];
if (node.isPostfix)
{
dest.write(expr + op);
}
else
{
dest.write(op + expr);
}
}
private static void process(IdentifierNode node)
{
if (node.isAttr())
{
dest.write("attribute(\"");
dest.write(node.name);
dest.write("\")");
}
else
{
dest.write(node.name);
}
}
private static void process(VariableBindingNode node)
{
System.err.println("Fix me!!! VariableBindingNode");
}
private static void processLiteral(Node node)
{
if (node instanceof LiteralNumberNode)
{
LiteralNumberNode numberNode = (LiteralNumberNode) node;
dest.write(numberNode.value);
if (numberNode.value.indexOf('.') != -1)
{
dest.write("f");
}
}
else if (node instanceof LiteralNullNode)
{
dest.write(BcCodeCs.NULL);
}
else if (node instanceof LiteralBooleanNode)
{
LiteralBooleanNode booleanNode = (LiteralBooleanNode) node;
dest.write(booleanNode.value ? "true" : "false");
}
else if (node instanceof LiteralStringNode)
{
LiteralStringNode stringNode = (LiteralStringNode) node;
dest.write(BcCodeCs.construct(classString, String.format("\"%s\"", stringNode.value)));
}
else if (node instanceof LiteralRegExpNode)
{
assert false : "LiteralRegExpNode";
}
else if (node instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) node;
ArgumentListNode elementlist = arrayNode.elementlist;
BcTypeNode type = null;
WriteDestination elementDest = new ListWriteDestination();
pushDest(elementDest);
int elementIndex = 0;
for (Node elementNode : elementlist.items)
{
process(elementNode);
if (++elementIndex < elementlist.items.size())
{
elementDest.write(", ");
}
}
popDest();
dest.writef("__NEWARRAY(Foo, %s)", elementDest);
}
else if (node instanceof LiteralObjectNode)
{
assert false : "LiteralObjectNode";
}
else
{
assert false : node.getClass();
}
}
private static void process(IfStatementNode node)
{
ListWriteDestination condDest = new ListWriteDestination();
pushDest(condDest);
process(node.condition);
popDest();
dest.writelnf("if(%s)", condDest);
if (node.thenactions != null)
{
ListWriteDestination thenDest = new ListWriteDestination();
pushDest(thenDest);
process(node.thenactions);
popDest();
dest.writeln(thenDest);
}
else
{
writeEmptyBlock();
}
if (node.elseactions != null)
{
ListWriteDestination elseDest = new ListWriteDestination();
pushDest(elseDest);
process(node.elseactions);
popDest();
dest.writeln("else");
dest.writeln(elseDest);
}
}
private static void process(ConditionalExpressionNode node)
{
ListWriteDestination condDest = new ListWriteDestination();
pushDest(condDest);
process(node.condition);
popDest();
ListWriteDestination thenDest = new ListWriteDestination();
pushDest(thenDest);
process(node.thenexpr);
popDest();
ListWriteDestination elseDest = new ListWriteDestination();
pushDest(elseDest);
process(node.elseexpr);
popDest();
dest.writef("((%s) ? (%s) : (%s))", condDest, thenDest, elseDest);
}
private static void process(WhileStatementNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
dest.writelnf("while(%s)", exprDest);
if (node.statement != null)
{
ListWriteDestination statementDest = new ListWriteDestination();
pushDest(statementDest);
process(node.statement);
popDest();
dest.writeln(statementDest);
}
else
{
writeEmptyBlock();
}
}
private static void process(ForStatementNode node)
{
boolean isForEach = node.test instanceof HasNextNode;
if (isForEach)
{
// get iterable collection expression
assert node.initialize != null;
assert node.initialize instanceof ListNode : node.initialize.getClass();
ListNode list = (ListNode) node.initialize;
assert list.items.size() == 2 : list.items.size();
StoreRegisterNode register = (StoreRegisterNode) list.items.get(1);
CoerceNode coerce = (CoerceNode) register.expr;
ListWriteDestination collection = new ListWriteDestination();
pushDest(collection);
process(coerce.expr);
popDest();
BcTypeNode collectionType = evaluateType(coerce.expr);
assert collectionType != null;
assert node.statement != null;
assert node.statement instanceof StatementListNode : node.statement.getClass();
StatementListNode statements = (StatementListNode) node.statement;
assert statements.items.size() == 2;
// get iteration
ExpressionStatementNode child1 = (ExpressionStatementNode) statements.items.get(0);
MemberExpressionNode child2 = (MemberExpressionNode) child1.expr;
SetExpressionNode child3 = (SetExpressionNode) child2.selector;
String loopVarName = null;
if (child3.expr instanceof QualifiedIdentifierNode)
{
QualifiedIdentifierNode identifier = (QualifiedIdentifierNode) child3.expr;
loopVarName = BcCodeCs.identifier(identifier.name);
}
else if (child3.expr instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) child3.expr;
loopVarName = BcCodeCs.identifier(identifier.name);
}
else
{
assert false : child3.expr.getClass();
}
BcVariableDeclaration loopVar = findDeclaredVar(loopVarName);
assert loopVar != null : loopVarName;
// get loop body
dest.writelnf("for (%s::Iterator __it = %s->__internalIterator(); __it.hasNext();)", BcCodeCs.type(collectionType), collection);
Node bodyNode = statements.items.get(1);
if (bodyNode != null)
{
assert bodyNode instanceof StatementListNode : bodyNode.getClass();
StatementListNode statementsNode = (StatementListNode) bodyNode;
writeBlockOpen(dest);
dest.writelnf("%s = __it.next();", loopVarName);
ObjectList<Node> items = statementsNode.items;
for (Node itemNode : items)
{
process(itemNode);
}
writeBlockClose(dest);
}
else
{
writeEmptyBlock();
}
}
else
{
ListWriteDestination initialize = new ListWriteDestination();
ListWriteDestination test = new ListWriteDestination();
ListWriteDestination increment = new ListWriteDestination();
if (node.initialize != null)
{
pushDest(initialize);
process(node.initialize);
popDest();
}
if (node.test != null)
{
pushDest(test);
process(node.test);
popDest();
}
if (node.increment != null)
{
increment = new ListWriteDestination();
pushDest(increment);
process(node.increment);
popDest();
}
dest.writelnf("for (%s; %s; %s)", initialize, test, increment);
process(node.statement);
}
}
private static void process(DoStatementNode node)
{
}
private static void process(SwitchStatementNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
dest.writelnf("switch(%s)", expr);
writeBlockOpen(dest);
if (node.statements != null)
{
ObjectList<Node> statements = node.statements.items;
for (Node statement : statements)
{
if (statement instanceof CaseLabelNode)
{
CaseLabelNode caseLabel = (CaseLabelNode)statement;
Node label = caseLabel.label;
if (label == null)
{
dest.writeln("default:");
}
else
{
ListWriteDestination caseDest = new ListWriteDestination();
pushDest(caseDest);
process(label);
popDest();
dest.writelnf("case %s:", caseDest);
}
writeBlockOpen(dest);
}
else if (statement instanceof BreakStatementNode)
{
process(statement);
writeBlockClose(dest);
}
else
{
process(statement);
}
}
}
writeBlockClose(dest);
}
private static void process(TryStatementNode node)
{
}
private static void process(ThrowStatementNode node)
{
}
private static void process(BinaryExpressionNode node)
{
ListWriteDestination ldest = new ListWriteDestination();
ListWriteDestination rdest = new ListWriteDestination();
pushDest(ldest);
process(node.lhs);
popDest();
pushDest(rdest);
process(node.rhs);
popDest();
if (node.op == Tokens.IS_TOKEN)
{
dest.write(BcCodeCs.operatorIs(ldest, rdest));
}
else if (node.op == Tokens.AS_TOKEN)
{
assert false;
}
else
{
dest.writef("%s %s %s", ldest, Tokens.tokenToString[-node.op], rdest);
}
}
private static void process(UnaryExpressionNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
switch (node.op)
{
case Tokens.NOT_TOKEN:
dest.writef("!(%s)", expr);
break;
case Tokens.MINUS_TOKEN:
dest.writef("-%s", expr);
break;
default:
assert false : node.op;
}
}
private static void process(ReturnStatementNode node)
{
assert !node.finallyInserted;
dest.write("return");
if (node.expr != null)
{
dest.write(" ");
process(node.expr);
}
dest.writeln(";");
}
private static void process(BreakStatementNode node)
{
dest.write("break");
if (node.id != null)
{
String id = BcCodeCs.identifier(node.id);
dest.write(" " + id);
}
dest.writeln(";");
}
private static void process(ThisExpressionNode node)
{
dest.write("this");
}
private static void process(SuperExpressionNode node)
{
String extendsClass = BcCodeCs.type(lastBcClass.getExtendsType());
dest.write(extendsClass);
}
private static void process(SuperStatementNode node)
{
ArgumentListNode args = node.call.args;
ListWriteDestination argsDest = new ListWriteDestination();
if (args != null)
{
pushDest(argsDest);
int itemIndex = 0;
for (Node arg : args.items)
{
process(arg);
if (++itemIndex < args.items.size())
{
dest.write(", ");
}
}
popDest();
}
dest.writelnf("%s(%s);", BcCodeCs.superCallMarker, argsDest);
}
private static void process(BcFunctionDeclaration bcFunc)
{
List<BcVariableDeclaration> oldDeclaredVars = declaredVars;
lastBcFunction = bcFunc;
declaredVars = bcFunc.getDeclaredVars();
// get function statements
ListWriteDestination body = new ListWriteDestination();
pushDest(body);
process(bcFunc.getStatements());
popDest();
List<String> lines = body.getLines();
String lastLine = lines.get(lines.size() - 2);
if (lastLine.contains("return;"))
{
lines.remove(lines.size() - 2);
}
bcFunc.setBody(body);
declaredVars = oldDeclaredVars;
lastBcFunction = null;
}
private static void process(ExpressionStatementNode node)
{
process(node.expr);
dest.writeln(";");
}
private static void process(ListNode node)
{
ObjectList<Node> items = node.items;
for (Node item : items)
{
process(item);
}
}
private static void process(BcTypeNode typeNode)
{
if (!typeNode.isIntegral() && !typeNode.hasClassNode())
{
BcClassDefinitionNode classNode = findClass(typeNode.getNameEx());
assert classNode != null : typeNode.getNameEx();
typeNode.setClassNode(classNode);
}
}
private static BcClassDefinitionNode findClass(String name)
{
BcClassDefinitionNode builtinClass = findBuiltinClass(name);
if (builtinClass != null)
{
return builtinClass;
}
for (BcClassDefinitionNode bcClass : bcClasses)
{
if (bcClass.getClassType().getName().equals(name))
{
return bcClass;
}
}
return null;
}
private static BcClassDefinitionNode findBuiltinClass(String name)
{
return builtinClasses.get(name);
}
private static BcFunctionDeclaration findBuiltinFunc(String name)
{
return bcBuitinFunctions.get(name);
}
private static BcFunctionTypeNode findFunctionType(String identifier)
{
BcTypeNode foundType = findVariableType(identifier);
if (foundType instanceof BcFunctionTypeNode)
{
return (BcFunctionTypeNode) foundType;
}
return null;
}
private static BcTypeNode findVariableType(String indentifier)
{
if (indentifier.equals("this"))
{
return BcTypeNode.create(lastBcClass.getName());
}
BcTypeNode foundType = null;
if (lastBcFunction != null)
{
foundType = findVariableType(lastBcFunction.getDeclaredVars(), indentifier);
if (foundType != null)
{
return foundType;
}
}
return findVariableType(lastBcClass.getDeclaredVars(), indentifier);
}
private static BcTypeNode findVariableType(List<BcVariableDeclaration> vars, String indentifier)
{
for (BcVariableDeclaration var : vars)
{
if (var.getIdentifier().equals(indentifier))
{
return var.getType();
}
}
return null;
}
private static void write(File outputDir) throws IOException
{
for (BcClassDefinitionNode bcClass : bcClasses)
{
if (bcClass.isInterface())
{
writeIntefaceDefinition(bcClass, outputDir);
}
else
{
writeClassDefinition(bcClass, outputDir);
}
}
}
private static void writeIntefaceDefinition(BcClassDefinitionNode bcClass, File outputDir) throws IOException
{
String className = getClassName(bcClass);
String classExtends = getBaseClassName(bcClass);
src = new FileWriteDestination(new File(outputDir, className + ".cs"));
impl = null;
List<BcTypeNode> headerTypes = getHeaderTypedefs(bcClass);
src.writeln("namespace bc");
writeBlockOpen(src);
src.writelnf("public interface %s : %s", className, classExtends);
writeBlockOpen(src);
writeInterfaceFunctions(bcClass);
writeBlockClose(src);
writeBlockClose(src);
src.close();
}
private static void writeInterfaceFunctions(BcClassDefinitionNode bcClass)
{
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
String type = bcFunc.hasReturnType() ? BcCodeCs.typeRef(bcFunc.getReturnType()) : "void";
String name = BcCodeCs.identifier(bcFunc.getName());
if (bcFunc.isConstructor())
{
continue;
}
src.writef("%s %s(", type, name);
StringBuilder paramsBuffer = new StringBuilder();
StringBuilder argsBuffer = new StringBuilder();
List<BcFuncParam> params = bcFunc.getParams();
int paramIndex = 0;
for (BcFuncParam bcParam : params)
{
String paramType = BcCodeCs.type(bcParam.getType());
String paramName = BcCodeCs.identifier(bcParam.getIdentifier());
paramsBuffer.append(String.format("%s %s", paramType, paramName));
argsBuffer.append(paramName);
if (++paramIndex < params.size())
{
paramsBuffer.append(", ");
argsBuffer.append(", ");
}
}
src.write(paramsBuffer);
src.writeln(");");
}
}
private static void writeClassDefinition(BcClassDefinitionNode bcClass, File outputDir) throws IOException
{
String className = getClassName(bcClass);
String classExtends = getBaseClassName(bcClass);
src = new FileWriteDestination(new File(outputDir, className + ".cs"));
impl = new ListWriteDestination();
List<BcTypeNode> headerTypes = getHeaderTypedefs(bcClass);
List<BcTypeNode> implTypes = getImplementationTypedefs(bcClass);
src.writeln("namespace bc");
writeBlockOpen(src);
src.writelnf("public class %s : %s", className, classExtends);
writeBlockOpen(src);
writeFields(bcClass);
writeFunctions(bcClass);
writeBlockClose(src);
writeBlockClose(src);
src.close();
}
private static void writeHeaderTypes(WriteDestination dst, List<BcTypeNode> types)
{
for (BcTypeNode bcType : types)
{
if (bcType instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) bcType;
String genericName = BcCodeCs.type(vectorType.getGeneric());
String typeName = BcCodeCs.type(bcType);
dst.writelnf("typedef %s<%s> %s;", BcCodeCs.type(BcCodeCs.VECTOR_TYPE), BcCodeCs.type(genericName), typeName);
dst.writelnf("typedef %s::Ref %s;", typeName, BcCodeCs.type(typeName));
}
else
{
String typeName = BcCodeCs.type(bcType);
dst.writelnf("__TYPEREF_DEF(%s)", typeName);
}
}
}
private static void writeImplementationTypes(WriteDestination dst, List<BcTypeNode> types)
{
for (BcTypeNode type : types)
{
if (type instanceof BcVectorTypeNode)
{
System.err.println("Fix me!!! Vector in implementation");
}
else
{
String typeName = BcCodeCs.type(type);
dst.writelnf("#include \"%s.h\"", typeName);
}
}
}
private static void writeFields(BcClassDefinitionNode bcClass)
{
List<BcVariableDeclaration> fields = bcClass.getFields();
impl.writeln();
for (BcVariableDeclaration bcField : fields)
{
String type = BcCodeCs.type(bcField.getType());
String name = BcCodeCs.identifier(bcField.getIdentifier());
src.write(bcField.getVisiblity() + " ");
if (bcField.isStatic())
{
src.write("static ");
}
if (bcField.isConst())
{
src.write("const ");
}
src.writef("%s %s", type, name);
if (bcField.hasInitializer())
{
src.writef(" = %s", bcField.getInitializer());
}
src.writeln(";");
}
}
private static void writeFunctions(BcClassDefinitionNode bcClass)
{
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
String type = bcFunc.hasReturnType() ? BcCodeCs.type(bcFunc.getReturnType()) : "void";
String name = BcCodeCs.identifier(bcFunc.getName());
src.write(bcFunc.getVisiblity() + " ");
if (!bcFunc.isConstructor())
{
if (bcFunc.isStatic())
{
src.write("static ");
}
else
{
src.write("virtual ");
}
src.write(type + " ");
}
src.writef("%s(", name);
StringBuilder paramsBuffer = new StringBuilder();
List<BcFuncParam> params = bcFunc.getParams();
int paramIndex = 0;
for (BcFuncParam bcParam : params)
{
String paramType = BcCodeCs.type(bcParam.getType());
String paramName = BcCodeCs.identifier(bcParam.getIdentifier());
paramsBuffer.append(String.format("%s %s", paramType, paramName));
if (++paramIndex < params.size())
{
paramsBuffer.append(", ");
}
}
src.write(paramsBuffer);
src.writeln(")");
src.writeln(bcFunc.getBody());
}
}
private static void writeBlockOpen(WriteDestination dest)
{
dest.writeln("{");
dest.incTab();
}
private static void writeBlockClose(WriteDestination dest)
{
dest.decTab();
dest.writeln("}");
}
private static void writeEmptyBlock()
{
writeEmptyBlock(dest);
}
private static void writeBlankLine(WriteDestination dest)
{
dest.writeln();
}
private static void writeBlankLine()
{
src.writeln();
impl.writeln();
}
private static void writeEmptyBlock(WriteDestination dest)
{
writeBlockOpen(dest);
writeBlockClose(dest);
}
private static void pushDest(WriteDestination newDest)
{
destStack.push(dest);
dest = newDest;
}
private static void popDest()
{
dest = destStack.pop();
}
///////////////////////////////////////////////////////////////
// Helpers
private static BcFunctionDeclaration findFunction(String name)
{
return lastBcClass.findFunction(name);
}
private static BcVariableDeclaration findDeclaredVar(String name)
{
assert declaredVars != null;
for (BcVariableDeclaration var : declaredVars)
{
if (var.getIdentifier().equals(name))
return var;
}
return null;
}
private static List<BcTypeNode> getHeaderTypedefs(BcClassDefinitionNode bcClass)
{
List<BcTypeNode> includes = new ArrayList<BcTypeNode>();
tryAddUniqueType(includes, bcClass.getClassType());
if (bcClass.hasInterfaces())
{
List<BcTypeNode> interfaces = bcClass.getInterfaces();
for (BcTypeNode bcInterface : interfaces)
{
tryAddUniqueType(includes, bcInterface);
}
}
List<BcVariableDeclaration> classVars = bcClass.getDeclaredVars();
for (BcVariableDeclaration bcVar : classVars)
{
BcTypeNode type = bcVar.getType();
tryAddUniqueType(includes, type);
}
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
if (bcFunc.hasReturnType())
{
BcTypeNode returnType = bcFunc.getReturnType();
tryAddUniqueType(includes, returnType);
}
List<BcFuncParam> params = bcFunc.getParams();
for (BcFuncParam param : params)
{
BcTypeNode type = param.getType();
tryAddUniqueType(includes, type);
}
}
return includes;
}
private static List<BcTypeNode> getImplementationTypedefs(BcClassDefinitionNode bcClass)
{
List<BcTypeNode> includes = new ArrayList<BcTypeNode>();
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
List<BcVariableDeclaration> funcVars = bcFunc.getDeclaredVars();
for (BcVariableDeclaration var : funcVars)
{
BcTypeNode type = var.getType();
tryAddUniqueType(includes, type);
}
}
return includes;
}
private static void tryAddUniqueType(List<BcTypeNode> types, BcTypeNode type)
{
if (BcCodeCs.canBeClass(type))
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
tryAddUniqueType(types, vectorType.getGeneric());
}
if (!types.contains(type))
{
types.add(type);
}
}
}
private static String getClassName(BcClassDefinitionNode bcClass)
{
return BcCodeCs.type(bcClass.getName());
}
private static String getBaseClassName(BcClassDefinitionNode bcClass)
{
if (bcClass.hasExtendsType())
{
return BcCodeCs.type(bcClass.getExtendsType());
}
return BcCodeCs.type(classObject);
}
public static BcTypeNode evaluateType(Node node)
{
if (node instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) node;
return findIdentifierType(BcCodeCs.identifier(identifier));
}
if (node instanceof LiteralNumberNode)
{
LiteralNumberNode numberNode = (LiteralNumberNode) node;
return numberNode.value.indexOf('.') != -1 ? BcTypeNode.create("float") : BcTypeNode.create("int");
}
if (node instanceof LiteralStringNode)
{
return BcTypeNode.create(classString);
}
if (node instanceof LiteralBooleanNode)
{
return BcTypeNode.create("BOOL");
}
if (node instanceof LiteralNullNode)
{
return BcTypeNode.create("null");
}
if (node instanceof ListNode)
{
ListNode listNode = (ListNode) node;
assert listNode.items.size() == 1;
return evaluateType(listNode.items.get(0));
}
if (node instanceof ThisExpressionNode)
{
assert lastBcClass != null;
return lastBcClass.getClassType();
}
if (node instanceof MemberExpressionNode)
{
return evaluateMemberExpression((MemberExpressionNode) node);
}
if (node instanceof GetExpressionNode)
{
GetExpressionNode get = (GetExpressionNode) node;
return evaluateType(get.expr);
}
if (node instanceof ArgumentListNode)
{
ArgumentListNode args = (ArgumentListNode) node;
assert args.size() == 1;
return evaluateType(args.items.get(0));
}
// MemberExpressionNode expr = null;
// if (node instanceof TypeExpressionNode)
// {
// TypeExpressionNode typeNode = (TypeExpressionNode) node;
// expr = (MemberExpressionNode) typeNode.expr;
// }
// else if (node instanceof MemberExpressionNode)
// {
// expr = (MemberExpressionNode) node;
// }
// else
// {
// BcDebug.implementMe(node);
// }
//
// if (expr.selector instanceof GetExpressionNode)
// {
// GetExpressionNode selector = (GetExpressionNode) expr.selector;
// String name = ((IdentifierNode)selector.expr).name;
// if (name.equals("Function"))
// {
// assert false;
// return new BcFunctionTypeNode();
// }
//
// return BcTypeNode.create(name);
// }
//
// if (expr.selector instanceof ApplyTypeExprNode)
// {
// ApplyTypeExprNode selector = (ApplyTypeExprNode) expr.selector;
// String typeName = ((IdentifierNode)selector.expr).name;
//
// ListNode typeArgs = selector.typeArgs;
// assert typeArgs.size() == 1;
//
// BcTypeNode genericType = extractBcType(typeArgs.items.get(0));
// return new BcVectorTypeNode(typeName, genericType);
// }
//
// assert false : expr.selector.getClass();
return null;
}
private static BcTypeNode evaluateMemberExpression(MemberExpressionNode node)
{
BcClassDefinitionNode baseClass = lastBcClass;
boolean hasCallTarget = node.base != null;
if (hasCallTarget)
{
if (node.base instanceof MemberExpressionNode)
{
assert node.base instanceof MemberExpressionNode;
BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) node.base);
assert baseType != null;
baseClass = baseType.getClassNode();
assert baseClass != null;
}
else if (node.base instanceof ThisExpressionNode)
{
// we're good
}
else if (node.base instanceof SuperExpressionNode)
{
baseClass = baseClass.getExtendsType().getClassNode(); // get supertype
}
else if (node.base instanceof ListNode)
{
ListNode list = (ListNode) node.base;
assert list.size() == 1 : list.size();
assert list.items.get(0) instanceof MemberExpressionNode;
BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) list.items.get(0));
assert baseType != null;
baseClass = baseType.getClassNode();
assert baseClass != null;
}
else
{
assert false;
}
}
if (node.selector instanceof SelectorNode)
{
SelectorNode selector = (SelectorNode) node.selector;
if (selector.expr instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) selector.expr;
BcTypeNode identifierType = findIdentifierType(baseClass, identifier, hasCallTarget);
if (identifierType != null)
{
return identifierType;
}
else
{
if (baseClass.getName().equals(classXML))
{
return BcTypeNode.create(classXMLList); // dirty hack
}
else if (BcCodeCs.identifier(identifier).equals(BcCodeCs.thisCallMarker))
{
return lastBcClass.getClassType(); // this referes to the current class
}
else if (baseClass.getName().endsWith(classObject))
{
return BcTypeNode.create(classObject);
}
}
}
else if (selector.expr instanceof ArgumentListNode)
{
BcTypeNode baseClassType = baseClass.getClassType();
if (baseClassType instanceof BcVectorTypeNode)
{
BcVectorTypeNode bcVector = (BcVectorTypeNode) baseClassType;
return bcVector.getGeneric();
}
else
{
return BcTypeNode.create(classObject); // no generics
}
}
else
{
assert false;
}
}
else
{
assert false;
}
return null;
}
private static BcTypeNode findIdentifierType(BcClassDefinitionNode baseClass, IdentifierNode identifier, boolean hasCallTarget)
{
if (identifier.isAttr())
{
return BcTypeNode.create(classString); // hack
}
String name = BcNodeHelper.extractBcIdentifier(identifier);
// check if it's class
if (BcCodeCs.canBeClass(name))
{
BcClassDefinitionNode bcClass = findClass(name);
if (bcClass != null)
{
return bcClass.getClassType();
}
}
else if (BcCodeCs.isBasicType(name))
{
return BcTypeNode.create(name);
}
// search for local variable
if (!hasCallTarget && lastBcFunction != null)
{
BcVariableDeclaration bcVar = lastBcFunction.findVariable(name);
if (bcVar != null) return bcVar.getType();
}
// search for function
BcFunctionDeclaration bcFunc = baseClass.findFunction(name);
if (bcFunc != null || (bcFunc = findBuiltinFunc(name)) != null)
{
if (bcFunc.hasReturnType())
{
return bcFunc.getReturnType();
}
return BcTypeNode.create("void");
}
// search for field
BcVariableDeclaration bcField = baseClass.findField(name);
if (bcField != null)
{
return bcField.getType();
}
return null;
}
private static BcTypeNode extractBcType(Node node)
{
BcTypeNode bcType = BcNodeHelper.extractBcType(node);
if (bcType instanceof BcVectorTypeNode)
{
BcClassDefinitionNode vectorGenericClass = findBuiltinClass(classVector).clone();
vectorGenericClass.setClassType(bcType);
builtinClasses.put(bcType.getNameEx(), vectorGenericClass);
bcType.setClassNode(vectorGenericClass);
}
BcTypeNode.add(bcType.getNameEx(), bcType);
return bcType;
}
private static void generateFunctor(WriteDestination dest, String className)
{
// BcClassDefinitionNode bcClass = new BcClassDefinitionNode("Functor");
// bcClass.setExtendsType(new BcTypeNode("Object"));
//
// List<String> targetModifiers = new ArrayList<String>();
// targetModifiers.add("private");
//
// BcVariableDeclaration targetVar = new BcVariableDeclaration(new BcTypeNode("Object"), new BcIdentifierNode("target"));
// targetVar.setModifiers(targetModifiers);
// bcClass.add(targetVar);
//
// List<String> operatorModifiers = new ArrayList<String>();
// operatorModifiers.add("public");
//
// BcFunctionDeclaration operatorFunc = new BcFunctionDeclaration("operator()");
// operatorFunc.setModifiers(operatorModifiers);
}
}
| false | true |
private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String expr = exprDest.toString();
if (lastBcMemberType != null)
{
BcTypeNode memberType = lastBcMemberType;
lastBcMemberType = null;
if (node.expr instanceof IdentifierNode)
{
String identifier = expr;
BcClassDefinitionNode bcClass = memberType.getClassNode();
if (bcClass != null)
{
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
}
}
}
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(" << ");
process(elementNode);
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(" << ");
process(elementNode);
}
popDest();
dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest);
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (BcCodeCs.canBeClass(type) || BcCodeCs.isBasicType(type))
{
dest.writef("((%s)(%s))", BcCodeCs.type(exprDest.toString()), argsDest);
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
}
|
private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String expr = exprDest.toString();
if (lastBcMemberType != null)
{
BcTypeNode memberType = lastBcMemberType;
lastBcMemberType = null;
if (node.expr instanceof IdentifierNode)
{
String identifier = expr;
BcClassDefinitionNode bcClass = memberType.getClassNode();
if (bcClass != null)
{
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
}
}
}
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(".add(");
process(elementNode);
initDest.write(")");
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(" << ");
process(elementNode);
}
popDest();
dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest);
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (BcCodeCs.canBeClass(type) || BcCodeCs.isBasicType(type))
{
dest.writef("((%s)(%s))", BcCodeCs.type(exprDest.toString()), argsDest);
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
else
{
dest.writef("%s(%s)", exprDest, argsDest);
}
}
}
|
diff --git a/src/java/org/apache/commons/math/complex/ComplexUtils.java b/src/java/org/apache/commons/math/complex/ComplexUtils.java
index fe2c4ffa4..a736d3603 100644
--- a/src/java/org/apache/commons/math/complex/ComplexUtils.java
+++ b/src/java/org/apache/commons/math/complex/ComplexUtils.java
@@ -1,275 +1,278 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.complex;
import org.apache.commons.math.util.MathUtils;
/**
* Implementations of various transcendental functions for
* {@link org.apache.commons.math.complex.Complex} arguments.
*
* Reference:
* <ul>
* <li><a href="http://myweb.lmu.edu/dmsmith/ZMLIB.pdf">
* Multiple Precision Complex Arithmetic and Functions</a></li>
* </ul>
*
* @version $Revision$ $Date$
*/
public class ComplexUtils {
/**
* Default constructor.
*/
private ComplexUtils() {
super();
}
/**
* Compute the <a href="http://mathworld.wolfram.com/InverseCosine.html">
* inverse cosine</a> for the given complex argument.
* @param z the value whose inverse cosine is to be returned.
* @return the inverse cosine of <code>z</code>.
*/
public static Complex acos(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
return Complex.I.negate().multiply(log(z.add(
Complex.I.multiply(sqrt1z(z)))));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/InverseSine.html">
* inverse sine</a> for the given complex argument.
* @param z the value whose inverse sine is to be returned.
* @return the inverse sine of <code>z</code>.
*/
public static Complex asin(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
return Complex.I.negate().multiply(log(sqrt1z(z).add(
Complex.I.multiply(z))));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/InverseTangent.html">
* inverse tangent</a> for the given complex argument.
* @param z the value whose inverse tangent is to be returned.
* @return the inverse tangent of <code>z</code>.
*/
public static Complex atan(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
return Complex.I.multiply(
log(Complex.I.add(z).divide(Complex.I.subtract(z))))
.divide(new Complex(2.0, 0.0));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/Cosine.html">cosine</a>
* for the given complex argument.
* @param z the value whose cosine is to be returned.
* @return the cosine of <code>z</code>.
*/
public static Complex cos(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
return new Complex(Math.cos(a) * MathUtils.cosh(b),
-Math.sin(a) * MathUtils.sinh(b));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/HyperbolicCosine.html">
* hyperbolic cosine</a> for the given complex argument.
* @param z the value whose hyperbolic cosine is to be returned.
* @return the hyperbolic cosine of <code>z</code>.
*/
public static Complex cosh(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
return new Complex(MathUtils.cosh(a) * Math.cos(b),
MathUtils.sinh(a) * Math.sin(b));
}
/**
* Compute the
* <a href="http://mathworld.wolfram.com/ExponentialFunction.html">
* exponential function</a> for the given complex argument.
* @param z the value.
* @return <i>e</i><sup><code>z</code></sup>.
*/
public static Complex exp(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double b = z.getImaginary();
double expA = Math.exp(z.getReal());
double sinB = Math.sin(b);
double cosB = Math.cos(b);
return new Complex(expA * cosB, expA * sinB);
}
/**
* Compute the <a href="http://mathworld.wolfram.com/NaturalLogarithm.html">
* natural logarithm</a> for the given complex argument.
* @param z the value.
* @return ln <code>z</code>.
*/
public static Complex log(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
return new Complex(Math.log(z.abs()),
Math.atan2(z.getImaginary(), z.getReal()));
}
/**
* Returns of value of <code>y</code> raised to the power of <code>x</code>.
* @param y the base.
* @param x the exponent.
* @return <code>y</code><sup><code>z</code></sup>.
*/
public static Complex pow(Complex y, Complex x) {
return exp(x.multiply(log(y)));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/Sine.html">sine</a>
* for the given complex argument.
* @param z the value whose sine is to be returned.
* @return the sine of <code>z</code>.
*/
public static Complex sin(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
return new Complex(Math.sin(a) * MathUtils.cosh(b),
Math.cos(a) * MathUtils.sinh(b));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/HyperbolicSine.html">
* hyperbolic sine</a> for the given complex argument.
* @param z the value whose hyperbolic sine is to be returned.
* @return the hyperbolic sine of <code>z</code>.
*/
public static Complex sinh(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
return new Complex(MathUtils.sinh(a) * Math.cos(b),
MathUtils.cosh(a) * Math.sin(b));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/SquareRoot.html">squre
* root</a> for the given complex argument.
* @param z the value whose square root is to be returned.
* @return the square root of <code>z</code>.
*/
public static Complex sqrt(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
+ if (a == 0.0 && b == 0.0) {
+ return new Complex(0.0, 0.0);
+ }
double t = Math.sqrt((Math.abs(a) + z.abs()) / 2.0);
if (a >= 0.0) {
return new Complex(t, b / (2.0 * t));
} else {
- return new Complex(Math.abs(z.getImaginary()) / (2.0 * t),
+ return new Complex(Math.abs(b) / (2.0 * t),
MathUtils.indicator(b) * t);
}
}
/**
* Compute the <a href="http://mathworld.wolfram.com/SquareRoot.html">squre
* root of 1 - <code>z</code><sup>2</sup> for the given complex argument.
* @param z the value.
* @return the square root of 1 - <code>z</code><sup>2</sup>.
*/
public static Complex sqrt1z(Complex z) {
return sqrt(Complex.ONE.subtract(z.multiply(z)));
}
/**
* Compute the <a href="http://mathworld.wolfram.com/Tangent.html">
* tangent</a> for the given complex argument.
* @param z the value whose tangent is to be returned.
* @return the tangent of <code>z</code>.
*/
public static Complex tan(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a2 = 2.0 * z.getReal();
double b2 = 2.0 * z.getImaginary();
double d = Math.cos(a2) + MathUtils.cosh(b2);
return new Complex(Math.sin(a2) / d, MathUtils.sinh(b2) / d);
}
/**
* Compute the
* <a href="http://mathworld.wolfram.com/HyperbolicTangent.html">
* hyperbolic tangent</a> for the given complex argument.
* @param z the value whose hyperbolic tangent is to be returned.
* @return the hyperbolic tangent of <code>z</code>.
*/
public static Complex tanh(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a2 = 2.0 * z.getReal();
double b2 = 2.0 * z.getImaginary();
double d = MathUtils.cosh(a2) + Math.cos(b2);
return new Complex(MathUtils.sinh(a2) / d, Math.sin(b2) / d);
}
}
| false | true |
public static Complex sqrt(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
double t = Math.sqrt((Math.abs(a) + z.abs()) / 2.0);
if (a >= 0.0) {
return new Complex(t, b / (2.0 * t));
} else {
return new Complex(Math.abs(z.getImaginary()) / (2.0 * t),
MathUtils.indicator(b) * t);
}
}
|
public static Complex sqrt(Complex z) {
if (z.isNaN()) {
return Complex.NaN;
}
double a = z.getReal();
double b = z.getImaginary();
if (a == 0.0 && b == 0.0) {
return new Complex(0.0, 0.0);
}
double t = Math.sqrt((Math.abs(a) + z.abs()) / 2.0);
if (a >= 0.0) {
return new Complex(t, b / (2.0 * t));
} else {
return new Complex(Math.abs(b) / (2.0 * t),
MathUtils.indicator(b) * t);
}
}
|
diff --git a/JAVA/parser/src/ch/epfl/bbcf/parser/BEDParser.java b/JAVA/parser/src/ch/epfl/bbcf/parser/BEDParser.java
index 64ec74a..f5bdc8a 100644
--- a/JAVA/parser/src/ch/epfl/bbcf/parser/BEDParser.java
+++ b/JAVA/parser/src/ch/epfl/bbcf/parser/BEDParser.java
@@ -1,83 +1,83 @@
package ch.epfl.bbcf.parser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.epfl.bbcf.exception.ParsingException;
import ch.epfl.bbcf.feature.BEDFeature;
import ch.epfl.bbcf.feature.Track;
public class BEDParser extends Parser{
private Track cur_track;
/**
* pattern matching the track's attributes
*/
private static final Pattern trackAttributesPattern =
Pattern.compile("(\\w+=\\w+)|(\\w+=\".+\")");
/**
* if the track parameters are finished to read
*/
private boolean trackParametersRead;
public BEDParser(Processing type) {
super(type);
trackParametersRead=false;
}
@Override
protected void processLine(String line,Handler handler) throws ParsingException {
if(line.startsWith("track") || !trackParametersRead){
if(line.startsWith("track")){
cur_track = new Track();
}
trackParametersRead=false;
Matcher m = trackAttributesPattern.matcher(line);
if(m.find()){
String[]tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
while(m.find()){
tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
}
} else {
trackParametersRead = true;
newTrack(handler, cur_track);
processLine(line,handler);
}
} else {
Float score = null;
Integer strand = null;
String name = null;
String itemRgb=null;
String blockStarts=null;
String blockCount=null;
String blockSizes=null;
int start,end,thickStart = 0,thickEnd = 0;
String chromosome;
String[] chr_start_end_name_score_strand= line.split("\\s");
switch(chr_start_end_name_score_strand.length){
case 12:blockStarts = chr_start_end_name_score_strand[11];
case 11:blockSizes = chr_start_end_name_score_strand[10];
case 10:blockCount = chr_start_end_name_score_strand[9];
case 9:itemRgb = chr_start_end_name_score_strand[8];
case 8:thickEnd = getInt(chr_start_end_name_score_strand[7]);
case 7:thickStart = getInt(chr_start_end_name_score_strand[6]);
case 6:strand = getStrand(chr_start_end_name_score_strand[5]);
case 5:score = getScore(chr_start_end_name_score_strand[4]);
case 4:name = chr_start_end_name_score_strand[3];
case 3:
chromosome = (chr_start_end_name_score_strand[0]);
start = getInt(chr_start_end_name_score_strand[1]);
end = getInt(chr_start_end_name_score_strand[2]);
break;
- default: throw new ParsingException("the entry don't have required number of fields " +
- "(at least 3 : chromosome,start,end separated by spaces or tabs): ", lineNb);
+ default: throw new ParsingException("The entry doesn't have the required number of fields " +
+ "(at least 3: chromosome, start, end separated by spaces or tabs): ", lineNb);
}
BEDFeature current = new BEDFeature(chromosome,start,end,name,strand,score,thickStart,thickEnd,itemRgb,blockCount,blockSizes,blockStarts);
newFeature(handler, cur_track, current);
}
}
}
| true | true |
protected void processLine(String line,Handler handler) throws ParsingException {
if(line.startsWith("track") || !trackParametersRead){
if(line.startsWith("track")){
cur_track = new Track();
}
trackParametersRead=false;
Matcher m = trackAttributesPattern.matcher(line);
if(m.find()){
String[]tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
while(m.find()){
tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
}
} else {
trackParametersRead = true;
newTrack(handler, cur_track);
processLine(line,handler);
}
} else {
Float score = null;
Integer strand = null;
String name = null;
String itemRgb=null;
String blockStarts=null;
String blockCount=null;
String blockSizes=null;
int start,end,thickStart = 0,thickEnd = 0;
String chromosome;
String[] chr_start_end_name_score_strand= line.split("\\s");
switch(chr_start_end_name_score_strand.length){
case 12:blockStarts = chr_start_end_name_score_strand[11];
case 11:blockSizes = chr_start_end_name_score_strand[10];
case 10:blockCount = chr_start_end_name_score_strand[9];
case 9:itemRgb = chr_start_end_name_score_strand[8];
case 8:thickEnd = getInt(chr_start_end_name_score_strand[7]);
case 7:thickStart = getInt(chr_start_end_name_score_strand[6]);
case 6:strand = getStrand(chr_start_end_name_score_strand[5]);
case 5:score = getScore(chr_start_end_name_score_strand[4]);
case 4:name = chr_start_end_name_score_strand[3];
case 3:
chromosome = (chr_start_end_name_score_strand[0]);
start = getInt(chr_start_end_name_score_strand[1]);
end = getInt(chr_start_end_name_score_strand[2]);
break;
default: throw new ParsingException("the entry don't have required number of fields " +
"(at least 3 : chromosome,start,end separated by spaces or tabs): ", lineNb);
}
BEDFeature current = new BEDFeature(chromosome,start,end,name,strand,score,thickStart,thickEnd,itemRgb,blockCount,blockSizes,blockStarts);
newFeature(handler, cur_track, current);
}
}
|
protected void processLine(String line,Handler handler) throws ParsingException {
if(line.startsWith("track") || !trackParametersRead){
if(line.startsWith("track")){
cur_track = new Track();
}
trackParametersRead=false;
Matcher m = trackAttributesPattern.matcher(line);
if(m.find()){
String[]tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
while(m.find()){
tab = m.group().split("=");
cur_track.addAttribute(tab[0],tab[1]);
}
} else {
trackParametersRead = true;
newTrack(handler, cur_track);
processLine(line,handler);
}
} else {
Float score = null;
Integer strand = null;
String name = null;
String itemRgb=null;
String blockStarts=null;
String blockCount=null;
String blockSizes=null;
int start,end,thickStart = 0,thickEnd = 0;
String chromosome;
String[] chr_start_end_name_score_strand= line.split("\\s");
switch(chr_start_end_name_score_strand.length){
case 12:blockStarts = chr_start_end_name_score_strand[11];
case 11:blockSizes = chr_start_end_name_score_strand[10];
case 10:blockCount = chr_start_end_name_score_strand[9];
case 9:itemRgb = chr_start_end_name_score_strand[8];
case 8:thickEnd = getInt(chr_start_end_name_score_strand[7]);
case 7:thickStart = getInt(chr_start_end_name_score_strand[6]);
case 6:strand = getStrand(chr_start_end_name_score_strand[5]);
case 5:score = getScore(chr_start_end_name_score_strand[4]);
case 4:name = chr_start_end_name_score_strand[3];
case 3:
chromosome = (chr_start_end_name_score_strand[0]);
start = getInt(chr_start_end_name_score_strand[1]);
end = getInt(chr_start_end_name_score_strand[2]);
break;
default: throw new ParsingException("The entry doesn't have the required number of fields " +
"(at least 3: chromosome, start, end separated by spaces or tabs): ", lineNb);
}
BEDFeature current = new BEDFeature(chromosome,start,end,name,strand,score,thickStart,thickEnd,itemRgb,blockCount,blockSizes,blockStarts);
newFeature(handler, cur_track, current);
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java b/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
index 7dbc0abba..81928070a 100644
--- a/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
+++ b/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
@@ -1,91 +1,101 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.domain;
public class GeoCoordinates {
private Double latitude;
private Double longitude;
private Double altitude;
private String code;
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getAltitude() {
return altitude;
}
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static GeoCoordinates extractGeoCoordinate(String line) {
GeoCoordinates gc = null;
if (line != null && line.trim().length() > 0
&& !line.trim().equals("||") && !line.startsWith("||")) {
gc = new GeoCoordinates();
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
- gc.setLatitude(new Double(coordinates[0]));
- gc.setLongitude(new Double(coordinates[1]));
+ try {
+ gc.setLatitude(Double.parseDouble(coordinates[0]));
+ gc.setLongitude(Double.parseDouble(coordinates[1]));
+ } catch (NumberFormatException nfe) {
+ // if we can't parse the lat/lon, the whole operation should fail
+ return null;
+ }
} else {
return null;
}
if (coordinates.length > 2) {
if (coordinates[2] != null
&& coordinates[2].trim().length() > 0) {
- gc.setAltitude(new Double(coordinates[2]));
+ try {
+ gc.setAltitude(Double.parseDouble(coordinates[2]));
+ } catch (NumberFormatException nfe) {
+ // the altitude cannot be parsed as double, so set it to null
+ gc.setAltitude(null);
+ }
}
}
if (coordinates.length > 3) {
gc.setCode(coordinates[3]);
}
}
return gc;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GeoCoordinates:");
sb.append("\n--Latitude: " + this.latitude);
sb.append("\n--Longitude: " + this.longitude);
sb.append("\n--Altitude: " + this.altitude);
return sb.toString();
}
}
| false | true |
public static GeoCoordinates extractGeoCoordinate(String line) {
GeoCoordinates gc = null;
if (line != null && line.trim().length() > 0
&& !line.trim().equals("||") && !line.startsWith("||")) {
gc = new GeoCoordinates();
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
gc.setLatitude(new Double(coordinates[0]));
gc.setLongitude(new Double(coordinates[1]));
} else {
return null;
}
if (coordinates.length > 2) {
if (coordinates[2] != null
&& coordinates[2].trim().length() > 0) {
gc.setAltitude(new Double(coordinates[2]));
}
}
if (coordinates.length > 3) {
gc.setCode(coordinates[3]);
}
}
return gc;
}
|
public static GeoCoordinates extractGeoCoordinate(String line) {
GeoCoordinates gc = null;
if (line != null && line.trim().length() > 0
&& !line.trim().equals("||") && !line.startsWith("||")) {
gc = new GeoCoordinates();
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
try {
gc.setLatitude(Double.parseDouble(coordinates[0]));
gc.setLongitude(Double.parseDouble(coordinates[1]));
} catch (NumberFormatException nfe) {
// if we can't parse the lat/lon, the whole operation should fail
return null;
}
} else {
return null;
}
if (coordinates.length > 2) {
if (coordinates[2] != null
&& coordinates[2].trim().length() > 0) {
try {
gc.setAltitude(Double.parseDouble(coordinates[2]));
} catch (NumberFormatException nfe) {
// the altitude cannot be parsed as double, so set it to null
gc.setAltitude(null);
}
}
}
if (coordinates.length > 3) {
gc.setCode(coordinates[3]);
}
}
return gc;
}
|
diff --git a/src/main/java/de/codeinfection/quickwango/AntiGuest/AntiGuestPlayerListener.java b/src/main/java/de/codeinfection/quickwango/AntiGuest/AntiGuestPlayerListener.java
index 775d729..7a9e42a 100644
--- a/src/main/java/de/codeinfection/quickwango/AntiGuest/AntiGuestPlayerListener.java
+++ b/src/main/java/de/codeinfection/quickwango/AntiGuest/AntiGuestPlayerListener.java
@@ -1,313 +1,313 @@
package de.codeinfection.quickwango.AntiGuest;
import java.util.HashMap;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerPickupItemEvent;
/**
*
* @author CodeInfection
*/
public class AntiGuestPlayerListener extends PlayerListener
{
protected final AntiGuest plugin;
protected final HashMap<Player, Long> chatTimestamps;
protected final HashMap<Player, Long> pickupTimestamps;
protected final HashMap<Player, Long> pressureTimestamps;
protected final boolean lever;
protected final boolean button;
protected final boolean door;
protected final boolean pressureplate;
protected final boolean chest;
protected final boolean workbench;
protected final boolean furnace;
protected final boolean dispenser;
protected final boolean placeblock;
protected final boolean cake;
protected final boolean chat;
protected final boolean spam;
public AntiGuestPlayerListener(AntiGuest plugin)
{
this.plugin = plugin;
this.chatTimestamps = new HashMap<Player, Long>();
this.pickupTimestamps = new HashMap<Player, Long>();
this.pressureTimestamps = new HashMap<Player, Long>();
this.lever = this.plugin.preventions.get("lever");
this.button = this.plugin.preventions.get("button");
this.door = this.plugin.preventions.get("door");
this.pressureplate = this.plugin.preventions.get("pressureplate");
this.chest = this.plugin.preventions.get("chest");
this.workbench = this.plugin.preventions.get("workbench");
this.furnace = this.plugin.preventions.get("furnace");
this.dispenser = this.plugin.preventions.get("dispenser");
this.placeblock = this.plugin.preventions.get("placeblock");
this.cake = this.plugin.preventions.get("cake");
this.chat = this.plugin.preventions.get("chat");
this.spam = this.plugin.preventions.get("spam");
}
protected void noPickupMessage(Player player)
{
Long lastTime = this.pickupTimestamps.get(player);
long currentTime = System.currentTimeMillis();
if (lastTime == null || lastTime + AntiGuest.messageWaitTime < currentTime)
{
this.plugin.message(player, "pickup");
this.pickupTimestamps.put(player, currentTime);
}
}
protected void pressureMessage(Player player)
{
Long lastTime = this.pressureTimestamps.get(player);
long currentTime = System.currentTimeMillis();
if (lastTime == null || lastTime + AntiGuest.messageWaitTime < currentTime)
{
this.plugin.message(player, "pressureplate");
this.pressureTimestamps.put(player, currentTime);
}
}
protected boolean isPlayerChatLocked(Player player)
{
if (this.plugin.can(player, "spam"))
{
return false;
}
else
{
Long lastTime = this.chatTimestamps.get(player);
long currentTime = System.currentTimeMillis();
if (lastTime == null || lastTime + (this.plugin.chatLockDuration * 1000) < currentTime)
{
this.chatTimestamps.put(player, currentTime);
return false;
}
else
{
return true;
}
}
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
Action action = event.getAction();
Block block = event.getClickedBlock();
if (block == null)
{
return;
}
Material material = block.getType();
Material itemInHand = player.getItemInHand().getType();
AntiGuest.debug("Player interacted with " + material.toString());
if (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK)
{
if (this.door && (material == Material.WOODEN_DOOR || material == Material.IRON_DOOR || material == Material.TRAP_DOOR)) // doors
{
if (!this.plugin.can(player, "door"))
{
this.plugin.message(player, "door");
event.setCancelled(true);
return;
}
}
else if (this.lever && material == Material.LEVER) // lever
{
if (!this.plugin.can(player, "lever"))
{
this.plugin.message(player, "lever");
event.setCancelled(true);
return;
}
}
else if (this.button && material == Material.STONE_BUTTON) // buttons
{
if (!this.plugin.can(player, "button"))
{
this.plugin.message(player, "button");
event.setCancelled(true);
return;
}
}
}
if (action == Action.RIGHT_CLICK_BLOCK)
{
if (this.chest && material == Material.CHEST) // chests
{
if (!this.plugin.can(player, "chest"))
{
this.plugin.message(player, "chest");
event.setCancelled(true);
return;
}
}
else if (this.workbench && material == Material.WORKBENCH) // workbenches
{
if (!this.plugin.can(player, "workbench"))
{
this.plugin.message(player, "workbench");
event.setCancelled(true);
return;
}
}
else if (this.furnace && material == Material.FURNACE) // furnaces
{
if (!this.plugin.can(player, "furnace"))
{
this.plugin.message(player, "furnace");
event.setCancelled(true);
return;
}
}
else if (this.dispenser && material == Material.DISPENSER) // dispensers
{
if (!this.plugin.can(player, "dispenser"))
{
this.plugin.message(player, "dispenser");
event.setCancelled(true);
return;
}
}
else if (this.cake && material == Material.CAKE_BLOCK) // cakes
{
if (!this.plugin.can(player, "cake"))
{
this.plugin.message(player, "cake");
event.setCancelled(true);
return;
}
}
if (this.placeblock)
{
boolean allowed = this.plugin.can(player, "placeblock");
- if ((itemInHand == Material.MINECART || itemInHand == Material.STORAGE_MINECART))
+ if ((itemInHand == Material.MINECART || itemInHand == Material.STORAGE_MINECART || itemInHand == Material.POWERED_MINECART))
{
if ((material == Material.RAILS || material == Material.POWERED_RAIL || material == Material.DETECTOR_RAIL) && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
else if (itemInHand == Material.BOAT && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
}
else if (this.pressureplate && action == Action.PHYSICAL)
{
if (material == Material.WOOD_PLATE || material == Material.STONE_PLATE) // pressure plates
{
if (!this.plugin.can(player, "pressureplate"))
{
this.pressureMessage(player);
event.setCancelled(true);
return;
}
}
}
}
@Override
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "pickup"))
{
event.setCancelled(true);
this.noPickupMessage(player);
}
}
@Override
public void onPlayerChat(PlayerChatEvent event)
{
final Player player = event.getPlayer();
if (this.chat && !this.plugin.can(player, "chat"))
{
event.setCancelled(true);
this.plugin.message(player, "chat");
}
else if (this.spam && this.isPlayerChatLocked(player))
{
event.setCancelled(true);
this.plugin.message(player, "spam");
}
}
@Override
public void onPlayerBucketFill(PlayerBucketFillEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "bucket"))
{
event.setCancelled(true);
this.plugin.message(player, "bucket");
}
}
@Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "bucket"))
{
event.setCancelled(true);
this.plugin.message(player, "bucket");
}
}
@Override
public void onPlayerDropItem(PlayerDropItemEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "drop"))
{
event.setCancelled(true);
this.plugin.message(player, "drop");
}
}
@Override
public void onPlayerBedEnter(PlayerBedEnterEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "bed"))
{
event.setCancelled(true);
this.plugin.message(player, "bed");
}
}
@Override
public void onPlayerFish(PlayerFishEvent event)
{
final Player player = event.getPlayer();
if (!this.plugin.can(player, "fish"))
{
event.setCancelled(true);
this.plugin.message(player, "fish");
}
}
}
| true | true |
public void onPlayerInteract(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
Action action = event.getAction();
Block block = event.getClickedBlock();
if (block == null)
{
return;
}
Material material = block.getType();
Material itemInHand = player.getItemInHand().getType();
AntiGuest.debug("Player interacted with " + material.toString());
if (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK)
{
if (this.door && (material == Material.WOODEN_DOOR || material == Material.IRON_DOOR || material == Material.TRAP_DOOR)) // doors
{
if (!this.plugin.can(player, "door"))
{
this.plugin.message(player, "door");
event.setCancelled(true);
return;
}
}
else if (this.lever && material == Material.LEVER) // lever
{
if (!this.plugin.can(player, "lever"))
{
this.plugin.message(player, "lever");
event.setCancelled(true);
return;
}
}
else if (this.button && material == Material.STONE_BUTTON) // buttons
{
if (!this.plugin.can(player, "button"))
{
this.plugin.message(player, "button");
event.setCancelled(true);
return;
}
}
}
if (action == Action.RIGHT_CLICK_BLOCK)
{
if (this.chest && material == Material.CHEST) // chests
{
if (!this.plugin.can(player, "chest"))
{
this.plugin.message(player, "chest");
event.setCancelled(true);
return;
}
}
else if (this.workbench && material == Material.WORKBENCH) // workbenches
{
if (!this.plugin.can(player, "workbench"))
{
this.plugin.message(player, "workbench");
event.setCancelled(true);
return;
}
}
else if (this.furnace && material == Material.FURNACE) // furnaces
{
if (!this.plugin.can(player, "furnace"))
{
this.plugin.message(player, "furnace");
event.setCancelled(true);
return;
}
}
else if (this.dispenser && material == Material.DISPENSER) // dispensers
{
if (!this.plugin.can(player, "dispenser"))
{
this.plugin.message(player, "dispenser");
event.setCancelled(true);
return;
}
}
else if (this.cake && material == Material.CAKE_BLOCK) // cakes
{
if (!this.plugin.can(player, "cake"))
{
this.plugin.message(player, "cake");
event.setCancelled(true);
return;
}
}
if (this.placeblock)
{
boolean allowed = this.plugin.can(player, "placeblock");
if ((itemInHand == Material.MINECART || itemInHand == Material.STORAGE_MINECART))
{
if ((material == Material.RAILS || material == Material.POWERED_RAIL || material == Material.DETECTOR_RAIL) && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
else if (itemInHand == Material.BOAT && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
}
else if (this.pressureplate && action == Action.PHYSICAL)
{
if (material == Material.WOOD_PLATE || material == Material.STONE_PLATE) // pressure plates
{
if (!this.plugin.can(player, "pressureplate"))
{
this.pressureMessage(player);
event.setCancelled(true);
return;
}
}
}
}
|
public void onPlayerInteract(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
Action action = event.getAction();
Block block = event.getClickedBlock();
if (block == null)
{
return;
}
Material material = block.getType();
Material itemInHand = player.getItemInHand().getType();
AntiGuest.debug("Player interacted with " + material.toString());
if (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK)
{
if (this.door && (material == Material.WOODEN_DOOR || material == Material.IRON_DOOR || material == Material.TRAP_DOOR)) // doors
{
if (!this.plugin.can(player, "door"))
{
this.plugin.message(player, "door");
event.setCancelled(true);
return;
}
}
else if (this.lever && material == Material.LEVER) // lever
{
if (!this.plugin.can(player, "lever"))
{
this.plugin.message(player, "lever");
event.setCancelled(true);
return;
}
}
else if (this.button && material == Material.STONE_BUTTON) // buttons
{
if (!this.plugin.can(player, "button"))
{
this.plugin.message(player, "button");
event.setCancelled(true);
return;
}
}
}
if (action == Action.RIGHT_CLICK_BLOCK)
{
if (this.chest && material == Material.CHEST) // chests
{
if (!this.plugin.can(player, "chest"))
{
this.plugin.message(player, "chest");
event.setCancelled(true);
return;
}
}
else if (this.workbench && material == Material.WORKBENCH) // workbenches
{
if (!this.plugin.can(player, "workbench"))
{
this.plugin.message(player, "workbench");
event.setCancelled(true);
return;
}
}
else if (this.furnace && material == Material.FURNACE) // furnaces
{
if (!this.plugin.can(player, "furnace"))
{
this.plugin.message(player, "furnace");
event.setCancelled(true);
return;
}
}
else if (this.dispenser && material == Material.DISPENSER) // dispensers
{
if (!this.plugin.can(player, "dispenser"))
{
this.plugin.message(player, "dispenser");
event.setCancelled(true);
return;
}
}
else if (this.cake && material == Material.CAKE_BLOCK) // cakes
{
if (!this.plugin.can(player, "cake"))
{
this.plugin.message(player, "cake");
event.setCancelled(true);
return;
}
}
if (this.placeblock)
{
boolean allowed = this.plugin.can(player, "placeblock");
if ((itemInHand == Material.MINECART || itemInHand == Material.STORAGE_MINECART || itemInHand == Material.POWERED_MINECART))
{
if ((material == Material.RAILS || material == Material.POWERED_RAIL || material == Material.DETECTOR_RAIL) && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
else if (itemInHand == Material.BOAT && !allowed)
{
event.setCancelled(true);
this.plugin.message(player, "placeblock");
return;
}
}
}
else if (this.pressureplate && action == Action.PHYSICAL)
{
if (material == Material.WOOD_PLATE || material == Material.STONE_PLATE) // pressure plates
{
if (!this.plugin.can(player, "pressureplate"))
{
this.pressureMessage(player);
event.setCancelled(true);
return;
}
}
}
}
|
diff --git a/engine/src/main/java/com/adgsoftware/mydomo/engine/connector/openwebnet/CommandResultImpl.java b/engine/src/main/java/com/adgsoftware/mydomo/engine/connector/openwebnet/CommandResultImpl.java
index c1ac5b24..4e3a7744 100644
--- a/engine/src/main/java/com/adgsoftware/mydomo/engine/connector/openwebnet/CommandResultImpl.java
+++ b/engine/src/main/java/com/adgsoftware/mydomo/engine/connector/openwebnet/CommandResultImpl.java
@@ -1,101 +1,101 @@
package com.adgsoftware.mydomo.engine.connector.openwebnet;
import java.util.List;
import java.util.logging.Level;
import com.adgsoftware.mydomo.engine.Log;
import com.adgsoftware.mydomo.engine.Log.Session;
import com.adgsoftware.mydomo.engine.connector.CommandResult;
import com.adgsoftware.mydomo.engine.connector.CommandResultStatus;
import com.adgsoftware.mydomo.engine.connector.openwebnet.parser.ParseException;
import com.adgsoftware.mydomo.engine.controller.DimensionValue;
/*
* #%L
* MyDomoEngine
* %%
* Copyright (C) 2011 - 2013 A. de Giuli
* %%
* This file is part of MyDomo done by A. de Giuli (arnaud.degiuli(at)free.fr).
*
* MyDomo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyDomo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyDomo. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* CommandResult is the result of a command sent to gateway.
*/
public class CommandResultImpl implements CommandResult {
private String commandResult;
private CommandResultStatus status;
private Log log = new Log();
private Command parser;
public CommandResultImpl(String commandResult, CommandResultStatus status) {
this.commandResult = commandResult;
this.status = status;
- if (!Command.ACK.equals(commandResult) && !Command.NACK.equals(commandResult)) {
+ if (commandResult != null &&!Command.ACK.equals(commandResult) && !Command.NACK.equals(commandResult)) {
try {
parser = Command.getCommandAnalyser(commandResult);
} catch (ParseException e) {
log.log(Session.Command, Level.SEVERE, "Unknown command result [" + commandResult + "].");
}
}
}
public String getResult() {
return commandResult;
}
public CommandResultStatus getStatus() {
return status;
}
@Override
public String getWhat() {
if (parser != null) {
return parser.getWhatFromCommand();
} else {
return null;
}
}
@Override
public String getWho() {
if (parser != null) {
return parser.getWhoFromCommand();
} else {
return null;
}
}
@Override
public String getWhere() {
if (parser != null) {
return parser.getWhereFromCommand();
} else {
return null;
}
}
@Override
public List<DimensionValue> getDimensionList() {
if (parser != null) {
return parser.getDimensionListFromCommand();
} else {
return null;
}
}
}
| true | true |
public CommandResultImpl(String commandResult, CommandResultStatus status) {
this.commandResult = commandResult;
this.status = status;
if (!Command.ACK.equals(commandResult) && !Command.NACK.equals(commandResult)) {
try {
parser = Command.getCommandAnalyser(commandResult);
} catch (ParseException e) {
log.log(Session.Command, Level.SEVERE, "Unknown command result [" + commandResult + "].");
}
}
}
|
public CommandResultImpl(String commandResult, CommandResultStatus status) {
this.commandResult = commandResult;
this.status = status;
if (commandResult != null &&!Command.ACK.equals(commandResult) && !Command.NACK.equals(commandResult)) {
try {
parser = Command.getCommandAnalyser(commandResult);
} catch (ParseException e) {
log.log(Session.Command, Level.SEVERE, "Unknown command result [" + commandResult + "].");
}
}
}
|
diff --git a/org.caleydo.view.subgraph/src/org/caleydo/view/subgraph/GLMultiFormWindow.java b/org.caleydo.view.subgraph/src/org/caleydo/view/subgraph/GLMultiFormWindow.java
index fc67dc5ea..f95eb5f8f 100644
--- a/org.caleydo.view.subgraph/src/org/caleydo/view/subgraph/GLMultiFormWindow.java
+++ b/org.caleydo.view.subgraph/src/org/caleydo/view/subgraph/GLMultiFormWindow.java
@@ -1,124 +1,124 @@
/*******************************************************************************
* Caleydo - visualization for molecular biology - http://caleydo.org
*
* Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander
* Lex, Christian Partl, Johannes Kepler University Linz </p>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*******************************************************************************/
package org.caleydo.view.subgraph;
import java.util.List;
import java.util.Map.Entry;
import org.caleydo.core.view.opengl.layout2.GLElementAdapter;
import org.caleydo.core.view.opengl.layout2.util.GLElementViewSwitchingBar;
import org.caleydo.view.subgraph.GLSubGraph.MultiFormInfo;
/**
* @author Christian
*
*/
public class GLMultiFormWindow extends GLWindow {
protected final MultiFormInfo info;
protected final GLElementViewSwitchingBar viewSwitchingBar;
protected boolean showViewSwitchingBar = true;
public GLMultiFormWindow(String title, GLSubGraph view, MultiFormInfo info, boolean isScrollable) {
super(title, view);
this.info = info;
GLElementAdapter container = isScrollable ? new ScrollableGLElementAdapter(view, info.multiFormRenderer)
: new GLElementAdapter(view, info.multiFormRenderer, true);
info.container = container;
setContent(container);
viewSwitchingBar = new GLElementViewSwitchingBar(info.multiFormRenderer);
titleBar.add(titleBar.size() - 1, viewSwitchingBar);
viewSwitchingBar.setVisibility(EVisibility.NONE);
for (Entry<EEmbeddingID, List<Integer>> entry : info.embeddingIDToRendererIDs.entrySet()) {
for (Integer rendererID : entry.getValue()) {
String toolTip = null;
switch (entry.getKey()) {
case PATHWAY_LEVEL1:
toolTip = "Pathway";
break;
case PATHWAY_LEVEL2:
- toolTip = "Pathway Thumbnail with Context Paths";
+ toolTip = "Context Paths with Pathway Thumbnail";
break;
case PATHWAY_LEVEL3:
- toolTip = "Pathway Thumbnail";
+ toolTip = "ContextPaths";
break;
case PATHWAY_LEVEL4:
toolTip = "Minimize";
break;
case PATH_LEVEL1:
toolTip = "Selected Path with Detailed Experimental Data";
break;
case PATH_LEVEL2:
toolTip = "Selected Path";
break;
default:
break;
}
if (toolTip != null) {
viewSwitchingBar.setButtonToolTip(toolTip, rendererID);
}
}
}
}
public int getMinWidth() {
return Math.max(info.multiFormRenderer.getMinWidthPixels(), 230);
}
public int getMinHeight() {
return info.multiFormRenderer.getMinHeightPixels() + 20;
}
/**
* @return the info, see {@link #info}
*/
public MultiFormInfo getInfo() {
return info;
}
@Override
public void setActive(boolean active) {
super.setActive(active);
if (showViewSwitchingBar) {
if (active) {
viewSwitchingBar.setVisibility(EVisibility.VISIBLE);
} else {
viewSwitchingBar.setVisibility(EVisibility.NONE);
}
}
}
/**
* @param showViewSwitchingBar
* setter, see {@link showViewSwitchingBar}
*/
public void setShowViewSwitchingBar(boolean showViewSwitchingBar) {
this.showViewSwitchingBar = showViewSwitchingBar;
if (showViewSwitchingBar) {
viewSwitchingBar.setVisibility(EVisibility.VISIBLE);
} else {
viewSwitchingBar.setVisibility(EVisibility.NONE);
}
}
}
| false | true |
public GLMultiFormWindow(String title, GLSubGraph view, MultiFormInfo info, boolean isScrollable) {
super(title, view);
this.info = info;
GLElementAdapter container = isScrollable ? new ScrollableGLElementAdapter(view, info.multiFormRenderer)
: new GLElementAdapter(view, info.multiFormRenderer, true);
info.container = container;
setContent(container);
viewSwitchingBar = new GLElementViewSwitchingBar(info.multiFormRenderer);
titleBar.add(titleBar.size() - 1, viewSwitchingBar);
viewSwitchingBar.setVisibility(EVisibility.NONE);
for (Entry<EEmbeddingID, List<Integer>> entry : info.embeddingIDToRendererIDs.entrySet()) {
for (Integer rendererID : entry.getValue()) {
String toolTip = null;
switch (entry.getKey()) {
case PATHWAY_LEVEL1:
toolTip = "Pathway";
break;
case PATHWAY_LEVEL2:
toolTip = "Pathway Thumbnail with Context Paths";
break;
case PATHWAY_LEVEL3:
toolTip = "Pathway Thumbnail";
break;
case PATHWAY_LEVEL4:
toolTip = "Minimize";
break;
case PATH_LEVEL1:
toolTip = "Selected Path with Detailed Experimental Data";
break;
case PATH_LEVEL2:
toolTip = "Selected Path";
break;
default:
break;
}
if (toolTip != null) {
viewSwitchingBar.setButtonToolTip(toolTip, rendererID);
}
}
}
}
|
public GLMultiFormWindow(String title, GLSubGraph view, MultiFormInfo info, boolean isScrollable) {
super(title, view);
this.info = info;
GLElementAdapter container = isScrollable ? new ScrollableGLElementAdapter(view, info.multiFormRenderer)
: new GLElementAdapter(view, info.multiFormRenderer, true);
info.container = container;
setContent(container);
viewSwitchingBar = new GLElementViewSwitchingBar(info.multiFormRenderer);
titleBar.add(titleBar.size() - 1, viewSwitchingBar);
viewSwitchingBar.setVisibility(EVisibility.NONE);
for (Entry<EEmbeddingID, List<Integer>> entry : info.embeddingIDToRendererIDs.entrySet()) {
for (Integer rendererID : entry.getValue()) {
String toolTip = null;
switch (entry.getKey()) {
case PATHWAY_LEVEL1:
toolTip = "Pathway";
break;
case PATHWAY_LEVEL2:
toolTip = "Context Paths with Pathway Thumbnail";
break;
case PATHWAY_LEVEL3:
toolTip = "ContextPaths";
break;
case PATHWAY_LEVEL4:
toolTip = "Minimize";
break;
case PATH_LEVEL1:
toolTip = "Selected Path with Detailed Experimental Data";
break;
case PATH_LEVEL2:
toolTip = "Selected Path";
break;
default:
break;
}
if (toolTip != null) {
viewSwitchingBar.setButtonToolTip(toolTip, rendererID);
}
}
}
}
|
diff --git a/classes/com/sapienter/jbilling/client/signup/NewEntityAction.java b/classes/com/sapienter/jbilling/client/signup/NewEntityAction.java
index 8a3d4879..ede997ae 100644
--- a/classes/com/sapienter/jbilling/client/signup/NewEntityAction.java
+++ b/classes/com/sapienter/jbilling/client/signup/NewEntityAction.java
@@ -1,171 +1,172 @@
/*
The contents of this file are subject to the Jbilling Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.jbilling.com/JPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Original Code is jbilling.
The Initial Developer of the Original Code is Emiliano Conde.
Portions created by Sapienter Billing Software Corp. are Copyright
(C) Sapienter Billing Software Corp. All Rights Reserved.
Contributor(s): ______________________________________.
*/
/*
* Created on Feb 8, 2005
*
*/
package com.sapienter.jbilling.client.signup;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
import com.sapienter.jbilling.common.Constants;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.interfaces.UserSession;
import com.sapienter.jbilling.interfaces.UserSessionHome;
import com.sapienter.jbilling.server.entity.ContactDTO;
import com.sapienter.jbilling.server.user.CustomerDTOEx;
import com.sapienter.jbilling.server.user.UserDTOEx;
/**
* @author Emil
*/
public class NewEntityAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Logger log = Logger.getLogger(NewEntityAction.class);
String action = request.getParameter("action");
if (action == null || action.length() == 0) {
return null;
}
String retValue = null;
HttpSession session;
if (action.equals("setup")) {
session = request.getSession(false);
if (session != null) {
session.invalidate();
}
session = request.getSession();
// locale
String language = request.getParameter("language");
String country = request.getParameter("country");
Locale locale = null;
if (language == null || language.length() == 0) {
language = "en";
}
if (country == null || country.length() == 0) {
locale = new Locale(language);
country = "US";
} else {
locale = new Locale(language, country);
}
session.setAttribute(Globals.LOCALE_KEY, locale);
session.setAttribute("signup_language", language);
log.debug("Setup language to " +
session.getAttribute("signup_language"));
session.setAttribute("signup_country", country);
retValue = "edit";
} else if (action.equals("edit")) {
session = request.getSession(false);
DynaValidatorForm myForm = (DynaValidatorForm) form;
ActionErrors errors = new ActionErrors(myForm.validate(
mapping, request));
if (!errors.isEmpty()) {
saveErrors(request, errors);
return mapping.findForward("edit");
}
log.debug("now doing the entity creation");
// check this constructor out ... :p
ContactDTO contact = new ContactDTO(
null,
(String) myForm.get("company_name"),
(String) myForm.get("address1"),
(String) myForm.get("address2"),
(String) myForm.get("city"),
(String) myForm.get("state"),
(String) myForm.get("postal_code"),
(String) myForm.get("country"),
(String) myForm.get("last_name"),
(String) myForm.get("first_name"),
null, null, null,
- Integer.valueOf((String) myForm.get("phone_area")),
+ ((String)myForm.get("phone_area")).length() == 0 ?
+ null : Integer.valueOf((String) myForm.get("phone_area")),
(String) myForm.get("phone_number"),
null, null, null,
(String) myForm.get("email"),
null,
new Integer(0), new Integer(1),null);
UserDTOEx user = new UserDTOEx();
user.setUserName((String) myForm.get("user_name"));
user.setPassword((String) myForm.get("password"));
user.setMainRoleId(Constants.TYPE_CUSTOMER);
CustomerDTOEx cust = new CustomerDTOEx();
cust.setInvoiceDeliveryMethodId(Constants.D_METHOD_EMAIL);
user.setCustomerDto(cust);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome UserHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = UserHome.create();
log.debug("Using language " +
session.getAttribute("signup_language"));
Integer entityId = userSession.createEntity(contact, user,
null, null,
(String) session.getAttribute("signup_language"), null);
// refresh the jbilling table
RefreshBettyTable toCall = new RefreshBettyTable(null);
toCall.refresh();
// store message
ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("newEntity.welcome", entityId.toString(),
user.getUserName(), user.getPassword()));
saveMessages(request, messages);
retValue = "done";
} catch (Exception e) {
log.debug("Exception ", e);
}
}
return mapping.findForward(retValue);
}
}
| true | true |
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Logger log = Logger.getLogger(NewEntityAction.class);
String action = request.getParameter("action");
if (action == null || action.length() == 0) {
return null;
}
String retValue = null;
HttpSession session;
if (action.equals("setup")) {
session = request.getSession(false);
if (session != null) {
session.invalidate();
}
session = request.getSession();
// locale
String language = request.getParameter("language");
String country = request.getParameter("country");
Locale locale = null;
if (language == null || language.length() == 0) {
language = "en";
}
if (country == null || country.length() == 0) {
locale = new Locale(language);
country = "US";
} else {
locale = new Locale(language, country);
}
session.setAttribute(Globals.LOCALE_KEY, locale);
session.setAttribute("signup_language", language);
log.debug("Setup language to " +
session.getAttribute("signup_language"));
session.setAttribute("signup_country", country);
retValue = "edit";
} else if (action.equals("edit")) {
session = request.getSession(false);
DynaValidatorForm myForm = (DynaValidatorForm) form;
ActionErrors errors = new ActionErrors(myForm.validate(
mapping, request));
if (!errors.isEmpty()) {
saveErrors(request, errors);
return mapping.findForward("edit");
}
log.debug("now doing the entity creation");
// check this constructor out ... :p
ContactDTO contact = new ContactDTO(
null,
(String) myForm.get("company_name"),
(String) myForm.get("address1"),
(String) myForm.get("address2"),
(String) myForm.get("city"),
(String) myForm.get("state"),
(String) myForm.get("postal_code"),
(String) myForm.get("country"),
(String) myForm.get("last_name"),
(String) myForm.get("first_name"),
null, null, null,
Integer.valueOf((String) myForm.get("phone_area")),
(String) myForm.get("phone_number"),
null, null, null,
(String) myForm.get("email"),
null,
new Integer(0), new Integer(1),null);
UserDTOEx user = new UserDTOEx();
user.setUserName((String) myForm.get("user_name"));
user.setPassword((String) myForm.get("password"));
user.setMainRoleId(Constants.TYPE_CUSTOMER);
CustomerDTOEx cust = new CustomerDTOEx();
cust.setInvoiceDeliveryMethodId(Constants.D_METHOD_EMAIL);
user.setCustomerDto(cust);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome UserHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = UserHome.create();
log.debug("Using language " +
session.getAttribute("signup_language"));
Integer entityId = userSession.createEntity(contact, user,
null, null,
(String) session.getAttribute("signup_language"), null);
// refresh the jbilling table
RefreshBettyTable toCall = new RefreshBettyTable(null);
toCall.refresh();
// store message
ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("newEntity.welcome", entityId.toString(),
user.getUserName(), user.getPassword()));
saveMessages(request, messages);
retValue = "done";
} catch (Exception e) {
log.debug("Exception ", e);
}
}
return mapping.findForward(retValue);
}
|
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Logger log = Logger.getLogger(NewEntityAction.class);
String action = request.getParameter("action");
if (action == null || action.length() == 0) {
return null;
}
String retValue = null;
HttpSession session;
if (action.equals("setup")) {
session = request.getSession(false);
if (session != null) {
session.invalidate();
}
session = request.getSession();
// locale
String language = request.getParameter("language");
String country = request.getParameter("country");
Locale locale = null;
if (language == null || language.length() == 0) {
language = "en";
}
if (country == null || country.length() == 0) {
locale = new Locale(language);
country = "US";
} else {
locale = new Locale(language, country);
}
session.setAttribute(Globals.LOCALE_KEY, locale);
session.setAttribute("signup_language", language);
log.debug("Setup language to " +
session.getAttribute("signup_language"));
session.setAttribute("signup_country", country);
retValue = "edit";
} else if (action.equals("edit")) {
session = request.getSession(false);
DynaValidatorForm myForm = (DynaValidatorForm) form;
ActionErrors errors = new ActionErrors(myForm.validate(
mapping, request));
if (!errors.isEmpty()) {
saveErrors(request, errors);
return mapping.findForward("edit");
}
log.debug("now doing the entity creation");
// check this constructor out ... :p
ContactDTO contact = new ContactDTO(
null,
(String) myForm.get("company_name"),
(String) myForm.get("address1"),
(String) myForm.get("address2"),
(String) myForm.get("city"),
(String) myForm.get("state"),
(String) myForm.get("postal_code"),
(String) myForm.get("country"),
(String) myForm.get("last_name"),
(String) myForm.get("first_name"),
null, null, null,
((String)myForm.get("phone_area")).length() == 0 ?
null : Integer.valueOf((String) myForm.get("phone_area")),
(String) myForm.get("phone_number"),
null, null, null,
(String) myForm.get("email"),
null,
new Integer(0), new Integer(1),null);
UserDTOEx user = new UserDTOEx();
user.setUserName((String) myForm.get("user_name"));
user.setPassword((String) myForm.get("password"));
user.setMainRoleId(Constants.TYPE_CUSTOMER);
CustomerDTOEx cust = new CustomerDTOEx();
cust.setInvoiceDeliveryMethodId(Constants.D_METHOD_EMAIL);
user.setCustomerDto(cust);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome UserHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = UserHome.create();
log.debug("Using language " +
session.getAttribute("signup_language"));
Integer entityId = userSession.createEntity(contact, user,
null, null,
(String) session.getAttribute("signup_language"), null);
// refresh the jbilling table
RefreshBettyTable toCall = new RefreshBettyTable(null);
toCall.refresh();
// store message
ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("newEntity.welcome", entityId.toString(),
user.getUserName(), user.getPassword()));
saveMessages(request, messages);
retValue = "done";
} catch (Exception e) {
log.debug("Exception ", e);
}
}
return mapping.findForward(retValue);
}
|
diff --git a/Alkitab/src/yuku/alkitab/base/widget/ReadingPlanFloatMenu.java b/Alkitab/src/yuku/alkitab/base/widget/ReadingPlanFloatMenu.java
index 2b68d09a..35afb850 100644
--- a/Alkitab/src/yuku/alkitab/base/widget/ReadingPlanFloatMenu.java
+++ b/Alkitab/src/yuku/alkitab/base/widget/ReadingPlanFloatMenu.java
@@ -1,257 +1,257 @@
package yuku.alkitab.base.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import yuku.afw.V;
import yuku.alkitab.base.S;
import yuku.alkitab.base.ac.ReadingPlanActivity;
import yuku.alkitab.base.util.ReadingPlanManager;
import yuku.alkitab.debug.R;
import yuku.alkitab.util.IntArrayList;
public class ReadingPlanFloatMenu extends LinearLayout {
public boolean isActive;
public boolean isAnimating;
private long id;
private int dayNumber;
private int[] ariRanges;
private boolean[] readMarks;
private int sequence;
private ReadingPlanFloatMenuClickListener leftNavigationListener;
private ReadingPlanFloatMenuClickListener rightNavigationListener;
private ReadingPlanFloatMenuClickListener descriptionListener;
private ReadingPlanFloatMenuClickListener closeReadingModeListener;
private Button bDescription;
private ImageButton bLeft;
private ImageButton bRight;
private CheckBox cbTick;
private Toast tooltip;
private View view;
@Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
clearAnimation();
fadeoutAnimation(5000);
}
return super.onInterceptTouchEvent(ev);
}
public ReadingPlanFloatMenu(final Context context) {
super(context);
}
public ReadingPlanFloatMenu(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public void load(long readingPlanId, int dayNumber, int[] ariRanges, int sequence) {
this.id = readingPlanId;
this.dayNumber = dayNumber;
this.ariRanges = ariRanges;
this.sequence = sequence;
this.readMarks = new boolean[ariRanges.length / 2];
updateProgress();
prepareLayout();
updateLayout();
}
public void updateProgress() {
IntArrayList readingCodes = S.getDb().getAllReadingCodesByReadingPlanId(id);
readMarks = new boolean[ariRanges.length / 2];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, dayNumber);
}
private void prepareLayout() {
if (view != null) {
return;
}
view = LayoutInflater.from(new ContextThemeWrapper(getContext(), R.style.Theme_AppCompat)).inflate(R.layout.float_menu_reading_plan, this, true);
bDescription = V.get(view, R.id.bDescription);
bLeft = V.get(view, R.id.bNavLeft);
bRight = V.get(view, R.id.bNavRight);
cbTick = V.get(view, R.id.cbTick);
ImageButton bClose = V.get(view, R.id.bClose);
bLeft.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != 0) {
sequence += -1;
- leftNavigationListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
+ leftNavigationListener.onClick(ariRanges[sequence * 2], ariRanges[sequence * 2 + 1]);
updateLayout();
}
}
});
bRight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != ariRanges.length / 2 - 1) {
sequence += 1;
- rightNavigationListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
+ rightNavigationListener.onClick(ariRanges[sequence * 2], ariRanges[sequence * 2 + 1]);
updateLayout();
}
}
});
cbTick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
readMarks[sequence] = isChecked;
ReadingPlanManager.updateReadingPlanProgress(id, dayNumber, sequence, isChecked);
updateLayout();
}
});
bDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
descriptionListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
bClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
closeReadingModeListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
//tooltip
bLeft.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatPreviousReading);
return true;
}
});
bRight.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatNextReading);
return true;
}
});
cbTick.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatCheckMark);
return true;
}
});
bDescription.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatDescription);
return true;
}
});
bClose.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatClose);
return true;
}
});
}
private void showTooltip(final int resId) {
if (tooltip == null) {
tooltip = Toast.makeText(getContext(), resId, Toast.LENGTH_SHORT);
} else {
tooltip.setText(resId);
}
tooltip.show();
}
public void updateLayout() {
if (ariRanges == null || readMarks == null) {
return;
}
cbTick.setChecked(readMarks[sequence]);
final StringBuilder reference = ReadingPlanActivity.getReference(S.activeVersion, ariRanges[sequence * 2], ariRanges[sequence * 2 + 1]);
reference.append("\n");
reference.append(sequence + 1);
reference.append("/").append(ariRanges.length / 2);
bDescription.setText(reference);
bLeft.setEnabled(sequence != 0);
bRight.setEnabled(sequence != ariRanges.length / 2 - 1);
}
public void fadeoutAnimation(long startOffset) {
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
alphaAnimation.setStartOffset(startOffset);
alphaAnimation.setDuration(1000);
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(final Animation animation) {
ReadingPlanFloatMenu.this.isAnimating = true;
}
@Override
public void onAnimationEnd(final Animation animation) {
ReadingPlanFloatMenu.this.isAnimating = false;
ReadingPlanFloatMenu.this.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(final Animation animation) {}
});
this.startAnimation(alphaAnimation);
}
public long getReadingPlanId() {
return id;
}
public void setLeftNavigationClickListener(final ReadingPlanFloatMenuClickListener leftNavigationClickListener) {
this.leftNavigationListener = leftNavigationClickListener;
}
public void setRightNavigationClickListener(final ReadingPlanFloatMenuClickListener rightNavigationClickListener) {
this.rightNavigationListener = rightNavigationClickListener;
}
public void setDescriptionListener(final ReadingPlanFloatMenuClickListener descriptionListener) {
this.descriptionListener = descriptionListener;
}
public void setCloseReadingModeClickListener(final ReadingPlanFloatMenuClickListener closeReadingModeClickListener) {
this.closeReadingModeListener = closeReadingModeClickListener;
}
public interface ReadingPlanFloatMenuClickListener {
public void onClick(int ari_start, int ari_end);
}
}
| false | true |
private void prepareLayout() {
if (view != null) {
return;
}
view = LayoutInflater.from(new ContextThemeWrapper(getContext(), R.style.Theme_AppCompat)).inflate(R.layout.float_menu_reading_plan, this, true);
bDescription = V.get(view, R.id.bDescription);
bLeft = V.get(view, R.id.bNavLeft);
bRight = V.get(view, R.id.bNavRight);
cbTick = V.get(view, R.id.cbTick);
ImageButton bClose = V.get(view, R.id.bClose);
bLeft.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != 0) {
sequence += -1;
leftNavigationListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
updateLayout();
}
}
});
bRight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != ariRanges.length / 2 - 1) {
sequence += 1;
rightNavigationListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
updateLayout();
}
}
});
cbTick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
readMarks[sequence] = isChecked;
ReadingPlanManager.updateReadingPlanProgress(id, dayNumber, sequence, isChecked);
updateLayout();
}
});
bDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
descriptionListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
bClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
closeReadingModeListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
//tooltip
bLeft.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatPreviousReading);
return true;
}
});
bRight.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatNextReading);
return true;
}
});
cbTick.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatCheckMark);
return true;
}
});
bDescription.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatDescription);
return true;
}
});
bClose.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatClose);
return true;
}
});
}
|
private void prepareLayout() {
if (view != null) {
return;
}
view = LayoutInflater.from(new ContextThemeWrapper(getContext(), R.style.Theme_AppCompat)).inflate(R.layout.float_menu_reading_plan, this, true);
bDescription = V.get(view, R.id.bDescription);
bLeft = V.get(view, R.id.bNavLeft);
bRight = V.get(view, R.id.bNavRight);
cbTick = V.get(view, R.id.cbTick);
ImageButton bClose = V.get(view, R.id.bClose);
bLeft.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != 0) {
sequence += -1;
leftNavigationListener.onClick(ariRanges[sequence * 2], ariRanges[sequence * 2 + 1]);
updateLayout();
}
}
});
bRight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
if (sequence != ariRanges.length / 2 - 1) {
sequence += 1;
rightNavigationListener.onClick(ariRanges[sequence * 2], ariRanges[sequence * 2 + 1]);
updateLayout();
}
}
});
cbTick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
readMarks[sequence] = isChecked;
ReadingPlanManager.updateReadingPlanProgress(id, dayNumber, sequence, isChecked);
updateLayout();
}
});
bDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
descriptionListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
bClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
closeReadingModeListener.onClick(ariRanges[sequence], ariRanges[sequence + 1]);
}
});
//tooltip
bLeft.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatPreviousReading);
return true;
}
});
bRight.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatNextReading);
return true;
}
});
cbTick.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatCheckMark);
return true;
}
});
bDescription.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatDescription);
return true;
}
});
bClose.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
showTooltip(R.string.rp_floatClose);
return true;
}
});
}
|
diff --git a/testit/de/uni_koblenz/jgralabtest/graphmarkertest/TryGraphMarkers.java b/testit/de/uni_koblenz/jgralabtest/graphmarkertest/TryGraphMarkers.java
index 85f437200..7ed813753 100644
--- a/testit/de/uni_koblenz/jgralabtest/graphmarkertest/TryGraphMarkers.java
+++ b/testit/de/uni_koblenz/jgralabtest/graphmarkertest/TryGraphMarkers.java
@@ -1,68 +1,68 @@
package de.uni_koblenz.jgralabtest.graphmarkertest;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.graphmarker.DoubleEdgeMarker;
import de.uni_koblenz.jgralab.graphmarker.IntegerVertexMarker;
import de.uni_koblenz.jgralabtest.schemas.minimal.Link;
import de.uni_koblenz.jgralabtest.schemas.minimal.MinimalGraph;
import de.uni_koblenz.jgralabtest.schemas.minimal.MinimalSchema;
import de.uni_koblenz.jgralabtest.schemas.minimal.Node;
public class TryGraphMarkers {
/**
* @param args
*/
public static void main(String[] args) {
MinimalGraph graph = MinimalSchema.instance().createMinimalGraph(5, 5);
Node v1 = graph.createNode();
Node v2 = graph.createNode();
Node v3 = graph.createNode();
Node v4 = graph.createNode();
Link l1 = graph.createLink(v1, v2);
Link l2 = graph.createLink(v1, v3);
Link l3 = graph.createLink(v4, v3);
Link l4 = graph.createLink(v4, v2);
Link l5 = graph.createLink(v1, v4);
IntegerVertexMarker marker1 = new IntegerVertexMarker(
graph);
marker1.mark(v1, 1);
marker1.mark(v2, 2);
marker1.mark(v3, 3);
marker1.mark(v4, 4);
DoubleEdgeMarker marker2 = new DoubleEdgeMarker(
graph);
marker2.mark(l1, 0.1);
marker2.mark(l2, 0.2);
marker2.mark(l3, 0.3);
marker2.mark(l4, 0.4);
marker2.mark(l5, Double.NEGATIVE_INFINITY);
printAllMarks(graph, marker1, marker2);
graph.createLink(graph.createNode(), graph.createNode());
System.out.println(marker1.maxSize());
printAllMarks(graph, marker1, marker2);
System.out.println(marker2.size());
- marker2.setUnmarkedValue(Double.NEGATIVE_INFINITY);
- printAllMarks(graph, marker1, marker2);
- System.out.println(marker2.size());
+ // marker2.setUnmarkedValue(Double.NEGATIVE_INFINITY);
+ // printAllMarks(graph, marker1, marker2);
+ // System.out.println(marker2.size());
}
private static void printAllMarks(MinimalGraph graph,
IntegerVertexMarker marker1,
DoubleEdgeMarker marker2) {
for (Vertex current : graph.vertices()) {
System.out.println(current + " " + marker1.getMark(current));
}
for (Edge current : graph.edges()) {
System.out.println(current + " " + marker2.getMark(current));
}
}
}
| true | true |
public static void main(String[] args) {
MinimalGraph graph = MinimalSchema.instance().createMinimalGraph(5, 5);
Node v1 = graph.createNode();
Node v2 = graph.createNode();
Node v3 = graph.createNode();
Node v4 = graph.createNode();
Link l1 = graph.createLink(v1, v2);
Link l2 = graph.createLink(v1, v3);
Link l3 = graph.createLink(v4, v3);
Link l4 = graph.createLink(v4, v2);
Link l5 = graph.createLink(v1, v4);
IntegerVertexMarker marker1 = new IntegerVertexMarker(
graph);
marker1.mark(v1, 1);
marker1.mark(v2, 2);
marker1.mark(v3, 3);
marker1.mark(v4, 4);
DoubleEdgeMarker marker2 = new DoubleEdgeMarker(
graph);
marker2.mark(l1, 0.1);
marker2.mark(l2, 0.2);
marker2.mark(l3, 0.3);
marker2.mark(l4, 0.4);
marker2.mark(l5, Double.NEGATIVE_INFINITY);
printAllMarks(graph, marker1, marker2);
graph.createLink(graph.createNode(), graph.createNode());
System.out.println(marker1.maxSize());
printAllMarks(graph, marker1, marker2);
System.out.println(marker2.size());
marker2.setUnmarkedValue(Double.NEGATIVE_INFINITY);
printAllMarks(graph, marker1, marker2);
System.out.println(marker2.size());
}
|
public static void main(String[] args) {
MinimalGraph graph = MinimalSchema.instance().createMinimalGraph(5, 5);
Node v1 = graph.createNode();
Node v2 = graph.createNode();
Node v3 = graph.createNode();
Node v4 = graph.createNode();
Link l1 = graph.createLink(v1, v2);
Link l2 = graph.createLink(v1, v3);
Link l3 = graph.createLink(v4, v3);
Link l4 = graph.createLink(v4, v2);
Link l5 = graph.createLink(v1, v4);
IntegerVertexMarker marker1 = new IntegerVertexMarker(
graph);
marker1.mark(v1, 1);
marker1.mark(v2, 2);
marker1.mark(v3, 3);
marker1.mark(v4, 4);
DoubleEdgeMarker marker2 = new DoubleEdgeMarker(
graph);
marker2.mark(l1, 0.1);
marker2.mark(l2, 0.2);
marker2.mark(l3, 0.3);
marker2.mark(l4, 0.4);
marker2.mark(l5, Double.NEGATIVE_INFINITY);
printAllMarks(graph, marker1, marker2);
graph.createLink(graph.createNode(), graph.createNode());
System.out.println(marker1.maxSize());
printAllMarks(graph, marker1, marker2);
System.out.println(marker2.size());
// marker2.setUnmarkedValue(Double.NEGATIVE_INFINITY);
// printAllMarks(graph, marker1, marker2);
// System.out.println(marker2.size());
}
|
diff --git a/Compiler/java/AppleCoreCompiler/Syntax/Parser.java b/Compiler/java/AppleCoreCompiler/Syntax/Parser.java
index 21c6e43..96dd321 100644
--- a/Compiler/java/AppleCoreCompiler/Syntax/Parser.java
+++ b/Compiler/java/AppleCoreCompiler/Syntax/Parser.java
@@ -1,906 +1,902 @@
package AppleCoreCompiler.Syntax;
import java.io.*;
import java.util.*;
import java.math.*;
import AppleCoreCompiler.AST.*;
import AppleCoreCompiler.AST.Node;
import AppleCoreCompiler.AST.Node.*;
import AppleCoreCompiler.Errors.*;
import AppleCoreCompiler.Syntax.*;
public class Parser {
public static final BigInteger MAX_SIZE =
new BigInteger("255");
/**
* Construct a new Parser object with the specified input file
*/
public Parser(String sourceFileName) {
this.sourceFileName = sourceFileName;
}
/**
* The input file name
*/
private String sourceFileName;
/**
* Scanner to provide the token stream
*/
private Scanner scanner;
/**
* Main method for testing the parser
*/
public static void main(String args[])
throws ACCError, IOException
{
Parser parser = null;
try {
parser = new Parser(args[0]);
parser.debug = true;
System.err.println("Parsing " + args[0] + "...");
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println("usage: java Parser [filename]");
System.exit(1);
}
SourceFile sourceFile = parser.parse();
if (sourceFile != null) {
// Print out the AST
ASTPrintingPass app = new ASTPrintingPass(System.out);
app.runOn(sourceFile);
}
}
/**
* Parse an AppleCore source file.
*/
public SourceFile parse()
throws ACCError, IOException
{
SourceFile sourceFile = null;
FileReader fr = null;
try {
fr = new FileReader(sourceFileName);
scanner = new Scanner(new BufferedReader(fr));
scanner.getNextToken();
sourceFile = parseSourceFile();
}
finally {
if (fr != null) fr.close();
}
return sourceFile;
}
/**
* SourceFile ::= Decl*
*/
private SourceFile parseSourceFile()
throws SyntaxError, IOException
{
SourceFile sourceFile = new SourceFile();
sourceFile.name = sourceFileName;
setLineNumberOf(sourceFile);
while (scanner.getCurrentToken() != Token.END) {
Declaration decl = parseDecl();
if (decl == null) break;
sourceFile.decls.add(decl);
}
return sourceFile;
}
public boolean debug = false;
private void printStatus(String s) {
if (debug) {
System.err.print("Line " + scanner.getCurrentToken().lineNumber);
System.err.println(": " + s);
}
}
private void printStatus() {
printStatus("parsed " + scanner.getCurrentToken());
}
/**
* Decl ::= Const-Decl | Data-Decl | Var-Decl | Fn-Decl
* | Include-Decl
*/
private Declaration parseDecl()
throws SyntaxError, IOException
{
Declaration result = null;
Token token = scanner.getCurrentToken();
switch (token) {
case INCLUDE:
printStatus();
result = parseIncludeDecl();
break;
case CONST:
printStatus();
result = parseConstDecl();
break;
case DATA:
printStatus();
result = parseDataDecl();
break;
case VAR:
printStatus();
result = parseVarDecl(false);
break;
case FN:
printStatus();
scanner.getNextToken();
result = parseFunctionDecl();
break;
default:
throw SyntaxError.expected("declaration",
token);
}
return result;
}
/**
* Include-Decl ::= INCLUDE String-Const ';'
*/
private IncludeDecl parseIncludeDecl()
throws SyntaxError, IOException
{
IncludeDecl includeDecl = new IncludeDecl();
setLineNumberOf(includeDecl);
expectAndConsume(Token.INCLUDE);
expect(Token.STRING_CONST);
includeDecl.filename = parseStringConstant().value;
expectAndConsume(Token.SEMI);
return includeDecl;
}
/**
* Const-Decl ::= CONST Ident [Numeric-Const] ';'
*/
private ConstDecl parseConstDecl()
throws SyntaxError, IOException
{
ConstDecl constDecl = new ConstDecl();
setLineNumberOf(constDecl);
expectAndConsume(Token.CONST);
constDecl.label = parseName();
if (scanner.getCurrentToken() != Token.SEMI) {
constDecl.expr = parseExpression();
}
expectAndConsume(Token.SEMI);
return constDecl;
}
/**
* Data-Decl ::= DATA [Ident] Const ';'
*/
private DataDecl parseDataDecl()
throws SyntaxError, IOException
{
DataDecl dataDecl = new DataDecl();
setLineNumberOf(dataDecl);
expectAndConsume(Token.DATA);
String name = parsePossibleName();
Token token = scanner.getCurrentToken();
if (token==Token.STRING_CONST) {
dataDecl.label = name;
dataDecl.stringConstant = parseStringConstant();
// Check for unterminated string
if (scanner.getCurrentToken() == Token.BACKSLASH) {
scanner.getNextToken();
}
else {
dataDecl.isTerminatedString = true;
}
}
else if (token==Token.SEMI) {
Identifier ident = new Identifier();
setLineNumberOf(ident);
ident.name = name;
dataDecl.expr = ident;
}
else {
dataDecl.label = name;
dataDecl.expr = parseExpression();
}
expectAndConsume(Token.SEMI);
return dataDecl;
}
/**
* Var-Decl ::= VAR Ident ':' Size ['S'] ['=' Expr] ';'
*/
private VarDecl parseVarDecl(boolean isLocalVariable)
throws SyntaxError, IOException
{
printStatus("parsing variable declaration");
VarDecl varDecl = new VarDecl();
setLineNumberOf(varDecl);
expectAndConsume(Token.VAR);
varDecl.isLocalVariable = isLocalVariable;
varDecl.name = parseName();
expectAndConsume(Token.COLON);
varDecl.size = parseSize();
varDecl.isSigned = parseIsSigned();
if (scanner.getCurrentToken() == Token.EQUALS) {
scanner.getNextToken();
varDecl.init = parseExpression();
}
expectAndConsume(Token.SEMI);
return varDecl;
}
/**
* Fn-Decl ::= FN [':' Size ['S']] Ident '(' Params ')' Fn-Body
* Fn-Body ::= '{' Var-Decl* Stmt* '}' | ';'
*/
private FunctionDecl parseFunctionDecl()
throws SyntaxError, IOException
{
FunctionDecl functionDecl = new FunctionDecl();
setLineNumberOf(functionDecl);
if (scanner.getCurrentToken() == Token.COLON) {
scanner.getNextToken();
functionDecl.size = parseSize();
functionDecl.isSigned = parseIsSigned();
}
functionDecl.name = parseName();
expectAndConsume(Token.LPAREN);
parseFunctionParams(functionDecl.params);
expectAndConsume(Token.RPAREN);
if (scanner.getCurrentToken() == Token.LBRACE) {
scanner.getNextToken();
parseVarDecls(functionDecl.varDecls,true);
parseStatements(functionDecl.statements);
expectAndConsume(Token.RBRACE);
}
else {
expectAndConsume(Token.SEMI);
functionDecl.isExternal = true;
}
return functionDecl;
}
/**
* Params ::= [ Param (',' Param)* ]
* Param ::= IDENT ':' Size ['S']
*/
private void parseFunctionParams(List<VarDecl> params)
throws SyntaxError, IOException
{
String name = parsePossibleName();
while (name != null) {
printStatus("parsing function parameter");
VarDecl param = new VarDecl();
param.isLocalVariable = true;
param.isFunctionParam = true;
setLineNumberOf(param);
param.name = name;
expectAndConsume(Token.COLON);
param.size = parseSize();
param.isSigned = parseIsSigned();
params.add(param);
name = null;
if (scanner.getCurrentToken() == Token.COMMA) {
scanner.getNextToken();
name = parseName();
}
}
}
/**
* Var-Decls ::= Var-Decl*
*/
private void parseVarDecls(List<VarDecl> varDecls,
boolean isLocalVariable)
throws SyntaxError, IOException
{
while (scanner.getCurrentToken() == Token.VAR) {
VarDecl varDecl = parseVarDecl(isLocalVariable);
varDecls.add(varDecl);
}
}
/**
* Stmt-List ::= Stmt*
*/
private void parseStatements(List<Statement> statements)
throws SyntaxError, IOException
{
while (scanner.getCurrentToken() != Token.RBRACE) {
Statement statement = parseStatement();
statements.add(statement);
}
}
/**
* Stmt ::= If-Stmt | While-Stmt | Set-Stmt | Call-Stmt |
* Incr-Stmt | Decr-Stmt | Return-Stmt | Block-Stmt
*/
private Statement parseStatement()
throws SyntaxError, IOException
{
Statement result = null;
Token token = scanner.getCurrentToken();
switch (token) {
case IF:
result = parseIfStatement();
break;
case WHILE:
result = parseWhileStatement();
break;
case SET:
result = parseSetStatement();
break;
case INCR:
result = parseIncrStatement();
break;
case DECR:
result = parseDecrStatement();
break;
case RETURN:
result = parseReturnStatement();
break;
case LBRACE:
result = parseBlockStatement();
break;
default:
result = parseCallStatement();
break;
}
return result;
}
/**
* If-Stmt ::= IF '(' Expr ')' Stmt [ELSE Stmt]
*/
private IfStatement parseIfStatement()
throws SyntaxError, IOException
{
IfStatement ifStmt = new IfStatement();
setLineNumberOf(ifStmt);
expectAndConsume(Token.IF);
expectAndConsume(Token.LPAREN);
ifStmt.test = parseExpression();
expectAndConsume(Token.RPAREN);
ifStmt.thenPart = parseStatement();
if (scanner.getCurrentToken() == Token.ELSE) {
scanner.getNextToken();
ifStmt.elsePart = parseStatement();
}
return ifStmt;
}
/**
* While-Stmt ::= WHILE '(' Expr ')' Stmt
*/
private WhileStatement parseWhileStatement()
throws SyntaxError, IOException
{
WhileStatement whileStmt = new WhileStatement();
setLineNumberOf(whileStmt);
expectAndConsume(Token.WHILE);
expectAndConsume(Token.LPAREN);
whileStmt.test = parseExpression();
expectAndConsume(Token.RPAREN);
whileStmt.body = parseStatement();
return whileStmt;
}
/**
* Set-Stmt ::= SET Expr '=' Expr ';'
*/
private SetStatement parseSetStatement()
throws SyntaxError, IOException
{
SetStatement setStmt = new SetStatement();
setLineNumberOf(setStmt);
expectAndConsume(Token.SET);
setStmt.lhs = parseLValueExpression();
expectAndConsume(Token.EQUALS);
setStmt.rhs = parseExpression();
expectAndConsume(Token.SEMI);
return setStmt;
}
/**
* Incr-Stmt ::= INCR Expr ';'
*/
private IncrStatement parseIncrStatement()
throws SyntaxError, IOException
{
IncrStatement incrStmt = new IncrStatement();
setLineNumberOf(incrStmt);
expectAndConsume(Token.INCR);
incrStmt.expr = parseExpression();
expectAndConsume(Token.SEMI);
return incrStmt;
}
/**
* Decr-Stmt ::= DECR Expr ';'
*/
private DecrStatement parseDecrStatement()
throws SyntaxError, IOException
{
DecrStatement decrStmt = new DecrStatement();
setLineNumberOf(decrStmt);
expectAndConsume(Token.DECR);
decrStmt.expr = parseExpression();
expectAndConsume(Token.SEMI);
return decrStmt;
}
/**
* Return-Stmt ::= RETURN [Expr] ';'
*/
private ReturnStatement parseReturnStatement()
throws SyntaxError, IOException
{
ReturnStatement returnStmt = new ReturnStatement();
setLineNumberOf(returnStmt);
expectAndConsume(Token.RETURN);
if (scanner.getCurrentToken() != Token.SEMI) {
returnStmt.expr = parseExpression();
}
expectAndConsume(Token.SEMI);
return returnStmt;
}
/**
* Block-Stmt ::= '{' Stmt-List '}'
*/
private BlockStatement parseBlockStatement()
throws SyntaxError, IOException
{
BlockStatement blockStmt = new BlockStatement();
setLineNumberOf(blockStmt);
expectAndConsume(Token.LBRACE);
parseStatements(blockStmt.statements);
expectAndConsume(Token.RBRACE);
return blockStmt;
}
/**
* Call-Stmt ::= Call-Expr ';'
*/
private Statement parseCallStatement()
throws SyntaxError, IOException
{
CallStatement callStmt = new CallStatement();
setLineNumberOf(callStmt);
Expression expr = parseExpression();
if (!(expr instanceof CallExpression)) {
throw new SyntaxError("not a statement",
scanner.getLineNumber());
}
callStmt.expr = (CallExpression) expr;
expectAndConsume(Token.SEMI);
return callStmt;
}
/**
* LValueExpr ::= Ident | Indexed-Expr | Register-Expr |
* Parens-Expr
*/
private Expression parseLValueExpression()
throws SyntaxError, IOException
{
return parseExpression(true);
}
/**
* Expr ::= LValueExpr | Call-Expr | Set-Expr |
* Binop-Expr | Unop-Expr | Numeric-Const |
*/
private Expression parseExpression()
throws SyntaxError, IOException
{
return parseExpression(false);
}
private Expression parseExpression(boolean lvalue)
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
Expression result = null;
switch (token) {
case IDENT:
result = parseIdentifier();
break;
case CARET:
result = parseRegisterExpr();
break;
case LPAREN:
result = parseParensExpr();
break;
case CHAR_CONST:
case INT_CONST:
result = parseNumericConstant();
break;
default:
- if (!lvalue) {
- Node.UnopExpression.Operator op =
- getUnaryOperatorFor(token);
- if (op != null) {
- result = parseUnopExpr(op);
- }
+ Node.UnopExpression.Operator op =
+ getUnaryOperatorFor(token);
+ if (op != null) {
+ result = parseUnopExpr(op);
}
break;
}
if (result == null) {
- String msg = lvalue ? "lvalue expression" :
- "expression";
- throw SyntaxError.expected(msg, token);
+ throw SyntaxError.expected("expression", token);
}
while (true) {
// Check for binary op
Node.BinopExpression.Operator op =
getBinaryOperatorFor(scanner.getCurrentToken());
- if (op != null && !lvalue) {
+ if (op != null && (op != BinopExpression.Operator.EQUALS || !lvalue)) {
scanner.getNextToken();
return parseBinopExpression(result, op);
}
// Check for call expr
else if (scanner.getCurrentToken()
- == Token.LPAREN && !lvalue) {
+ == Token.LPAREN) {
result = parseCallExpression(result);
}
// Check for indexed expr
else if (scanner.getCurrentToken()
== Token.LBRACKET) {
result = parseIndexedExpression(result);
}
else return result;
}
}
/**
* IndexedExpr ::= Expr '[' Expr,Size ']'
*/
private IndexedExpression parseIndexedExpression(Expression indexed)
throws SyntaxError, IOException
{
IndexedExpression indexedExp = new IndexedExpression();
setLineNumberOf(indexedExp);
indexedExp.indexed = indexed;
expectAndConsume(Token.LBRACKET);
indexedExp.index = parseExpression();
expectAndConsume(Token.COMMA);
indexedExp.size = parseSize();
expectAndConsume(Token.RBRACKET);
return indexedExp;
}
/**
* Call-Expr ::= Expr '(' Args ')'
* Args ::= [Expr [',' Expr]*]
*/
private CallExpression parseCallExpression(Expression fn)
throws SyntaxError, IOException
{
CallExpression callExp = new CallExpression();
callExp.lineNumber = fn.lineNumber;
callExp.fn = fn;
expectAndConsume(Token.LPAREN);
if (scanner.getCurrentToken() == Token.RPAREN) {
printStatus();
scanner.getNextToken();
return callExp;
}
while (true) {
callExp.args.add(parseExpression());
if (scanner.getCurrentToken() != Token.COMMA)
break;
scanner.getNextToken();
}
expectAndConsume(Token.RPAREN);
return callExp;
}
/**
* Register-Expr ::= '^' Reg-Name
* Reg-Name ::= 'X' | 'Y' | 'S' | 'P' | 'A'
*/
private RegisterExpression parseRegisterExpr()
throws SyntaxError, IOException
{
RegisterExpression regExp = new RegisterExpression();
setLineNumberOf(regExp);
expectAndConsume(Token.CARET);
Token token = scanner.getCurrentToken();
Identifier ident = parseIdentifier();
if (ident.name.length() == 1) {
char name = ident.name.charAt(0);
for (RegisterExpression.Register reg :
RegisterExpression.Register.values()) {
if (reg.name == name) {
regExp.register = reg;
return regExp;
}
}
}
throw SyntaxError.expected("register name", token);
}
/**
* Unop-Expr ::= Unop Expr
* Unop ::= '@' | 'NOT' | '-'
*/
private UnopExpression parseUnopExpr(Node.UnopExpression.Operator op)
throws SyntaxError, IOException
{
UnopExpression unopExpr = new UnopExpression();
setLineNumberOf(unopExpr);
unopExpr.operator = op;
scanner.getNextToken();
unopExpr.expr = parseExpression();
return unopExpr;
}
/**
* Return the unary operator corresponding to the token, null if
* none.
*/
private Node.UnopExpression.Operator getUnaryOperatorFor(Token token) {
for (Node.UnopExpression.Operator op :
Node.UnopExpression.Operator.values()) {
if (token.stringValue.equals(op.symbol))
return op;
}
return null;
}
/**
* Parens-Expr ::= '(' Expr ')'
*/
private ParensExpression parseParensExpr()
throws SyntaxError, IOException
{
ParensExpression parensExp = new ParensExpression();
setLineNumberOf(parensExp);
expectAndConsume(Token.LPAREN);
parensExp.expr = parseExpression();
expectAndConsume(Token.RPAREN);
return parensExp;
}
/**
* Binop-Expr ::= Expr Binop Expr
* Binop ::= '=' | '>' | '<' | '<=' | '>=' |
* 'AND' | 'OR' | 'XOR' | '+' | '-' |
* '*' | '/' | '<<' | '>>'
*/
private BinopExpression parseBinopExpression(Expression left,
Node.BinopExpression.Operator op)
throws SyntaxError, IOException
{
BinopExpression result = new BinopExpression();
setLineNumberOf(result);
result.left = left;
result.operator = op;
Expression right = parseExpression();
if (right instanceof BinopExpression) {
BinopExpression binop = (BinopExpression) right;
if (op.precedence <= binop.operator.precedence) {
// Switch precedence
result.right = binop.left;
binop.left = result;
result = binop;
} else {
result.right = right;
}
} else {
result.right = right;
}
return result;
}
/**
* Return the binary operator corresponding to the token, null if
* none.
*/
private Node.BinopExpression.Operator getBinaryOperatorFor(Token token) {
for (Node.BinopExpression.Operator op :
Node.BinopExpression.Operator.values()) {
if (token.stringValue.equals(op.symbol))
return op;
}
return null;
}
/**
* Parse a size.
*/
private int parseSize()
throws SyntaxError, IOException
{
IntegerConstant intConstant = parseIntConstant();
if (intConstant.valueAsBigInteger().compareTo(BigInteger.ZERO) < 0 ||
intConstant.valueAsBigInteger().compareTo(MAX_SIZE) > 0) {
throw new SyntaxError(intConstant + " out of range",
scanner.getLineNumber());
}
return intConstant.valueAsBigInteger().intValue();
}
/**
* Look for an 'S' indicating a signed value. If it's there
* return true and advance the token stream; otherwise return
* false.
*/
private boolean parseIsSigned()
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
if (token == Token.IDENT && token.stringValue.equals("S")) {
scanner.getNextToken();
return true;
}
return false;
}
/**
* Parse and return an identifier if it's there. If not, return
* null.
*/
private Identifier parsePossibleIdentifier()
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
if (token == Token.IDENT) {
return parseIdentifier();
}
return null;
}
/**
* Expect and consume an identifier token and return an AST node
* for that token.
*/
private Identifier parseIdentifier()
throws SyntaxError, IOException
{
expect(Token.IDENT);
Token token = scanner.getCurrentToken();
Identifier ident = new Identifier();
setLineNumberOf(ident);
ident.name = token.stringValue;
scanner.getNextToken();
return ident;
}
/**
* Parse and return an identifier if it's there. If not, return
* null.
*/
private String parsePossibleName()
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
if (token == Token.IDENT) {
return parseName();
}
return null;
}
/**
* Parse an identifier token and extract the name.
*/
private String parseName()
throws SyntaxError, IOException
{
expect(Token.IDENT);
Token token = scanner.getCurrentToken();
String name = token.stringValue;
scanner.getNextToken();
return name;
}
/**
* Parse a string constant
*/
private StringConstant parseStringConstant()
throws SyntaxError, IOException
{
StringConstant stringConstant = new StringConstant();
setLineNumberOf(stringConstant);
Token token = scanner.getCurrentToken();
stringConstant.value = token.getStringValue();
scanner.getNextToken();
return stringConstant;
}
/**
* Numeric-Const ::= Int-Const | Char-Const
*/
private NumericConstant parseNumericConstant()
throws SyntaxError, IOException
{
IntegerConstant intConstant = parsePossibleIntConstant();
if (intConstant != null) return intConstant;
Token token = scanner.getCurrentToken();
if (token != Token.CHAR_CONST) {
throw SyntaxError.expected("numeric constant", token);
}
printStatus();
CharConstant charConstant = new CharConstant();
setLineNumberOf(charConstant);
charConstant.value = token.stringValue.charAt(0);
scanner.getNextToken();
return charConstant;
}
/**
* Parse an integer constant.
*/
private IntegerConstant parseIntConstant()
throws SyntaxError, IOException
{
IntegerConstant result = parsePossibleIntConstant();
if (result == null)
throw SyntaxError.expected ("integer constant",
scanner.getCurrentToken());
return result;
}
/**
* Try to get an integer constant. Return an integer constant
* object on success, null on failure.
*/
private IntegerConstant parsePossibleIntConstant()
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
IntegerConstant result = null;
switch (token) {
case INT_CONST:
result = new IntegerConstant();
result.wasHexInSource = token.wasHexInSource;
break;
}
if (result != null) {
printStatus();
setLineNumberOf(result);
result.setValue(token.getNumberValue());
scanner.getNextToken();
}
return result;
}
/**
* Check that the current token is the expected one; if not,
* report an error
*/
private void expect(Token token)
throws SyntaxError
{
Token currentToken = scanner.getCurrentToken();
if (token != currentToken)
throw SyntaxError.expected(token.expectedString(),
currentToken);
printStatus();
}
/**
* Check for the expected token, then consume it
*/
private Token expectAndConsume(Token token)
throws SyntaxError, IOException {
expect(token);
return scanner.getNextToken();
}
/**
* Set the line number of an AST node to the current line
* recorded in the scanner.
*/
private void setLineNumberOf(Node node) {
node.lineNumber = scanner.getLineNumber();
}
}
| false | true |
private Expression parseExpression(boolean lvalue)
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
Expression result = null;
switch (token) {
case IDENT:
result = parseIdentifier();
break;
case CARET:
result = parseRegisterExpr();
break;
case LPAREN:
result = parseParensExpr();
break;
case CHAR_CONST:
case INT_CONST:
result = parseNumericConstant();
break;
default:
if (!lvalue) {
Node.UnopExpression.Operator op =
getUnaryOperatorFor(token);
if (op != null) {
result = parseUnopExpr(op);
}
}
break;
}
if (result == null) {
String msg = lvalue ? "lvalue expression" :
"expression";
throw SyntaxError.expected(msg, token);
}
while (true) {
// Check for binary op
Node.BinopExpression.Operator op =
getBinaryOperatorFor(scanner.getCurrentToken());
if (op != null && !lvalue) {
scanner.getNextToken();
return parseBinopExpression(result, op);
}
// Check for call expr
else if (scanner.getCurrentToken()
== Token.LPAREN && !lvalue) {
result = parseCallExpression(result);
}
// Check for indexed expr
else if (scanner.getCurrentToken()
== Token.LBRACKET) {
result = parseIndexedExpression(result);
}
else return result;
}
}
|
private Expression parseExpression(boolean lvalue)
throws SyntaxError, IOException
{
Token token = scanner.getCurrentToken();
Expression result = null;
switch (token) {
case IDENT:
result = parseIdentifier();
break;
case CARET:
result = parseRegisterExpr();
break;
case LPAREN:
result = parseParensExpr();
break;
case CHAR_CONST:
case INT_CONST:
result = parseNumericConstant();
break;
default:
Node.UnopExpression.Operator op =
getUnaryOperatorFor(token);
if (op != null) {
result = parseUnopExpr(op);
}
break;
}
if (result == null) {
throw SyntaxError.expected("expression", token);
}
while (true) {
// Check for binary op
Node.BinopExpression.Operator op =
getBinaryOperatorFor(scanner.getCurrentToken());
if (op != null && (op != BinopExpression.Operator.EQUALS || !lvalue)) {
scanner.getNextToken();
return parseBinopExpression(result, op);
}
// Check for call expr
else if (scanner.getCurrentToken()
== Token.LPAREN) {
result = parseCallExpression(result);
}
// Check for indexed expr
else if (scanner.getCurrentToken()
== Token.LBRACKET) {
result = parseIndexedExpression(result);
}
else return result;
}
}
|
diff --git a/module/org.restlet/src/org/restlet/data/Response.java b/module/org.restlet/src/org/restlet/data/Response.java
index a37ed06e2..cccae283b 100644
--- a/module/org.restlet/src/org/restlet/data/Response.java
+++ b/module/org.restlet/src/org/restlet/data/Response.java
@@ -1,372 +1,380 @@
/*
* Copyright 2005-2006 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.data;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
/**
* Generic response sent by server connectors. It is then received by client
* connectors. Responses are uniform across all types of connectors, protocols
* and components.
*
* @see org.restlet.data.Request
* @see org.restlet.Restlet
* @author Jerome Louvel ([email protected])
*/
public class Response extends Message {
/** The set of methods allowed on the requested resource. */
private Set<Method> allowedMethods;
/** The authentication request sent by an origin server to a client. */
private ChallengeRequest challengeRequest;
/** The cookie settings provided by the server. */
private List<CookieSetting> cookieSettings;
/** The set of dimensions on which the response entity may vary. */
private Set<Dimension> dimensions;
/** The redirection reference. */
private Reference redirectRef;
/** The associated request. */
private Request request;
/** The server-specific information. */
private ServerInfo serverInfo;
/** The status. */
private Status status;
/**
* Constructor.
*
* @param request
* The request associated to this response.
*/
public Response(Request request) {
this.allowedMethods = null;
this.challengeRequest = null;
this.cookieSettings = null;
this.dimensions = null;
this.redirectRef = null;
this.request = request;
this.serverInfo = null;
this.status = Status.SUCCESS_OK;
}
/**
* Returns the set of methods allowed on the requested resource. This
* property only has to be updated when a status
* CLIENT_ERROR_METHOD_NOT_ALLOWED is set.
*
* @return The list of allowed methods.
*/
public Set<Method> getAllowedMethods() {
if (this.allowedMethods == null)
this.allowedMethods = new HashSet<Method>();
return this.allowedMethods;
}
/**
* Returns the authentication request sent by an origin server to a client.
*
* @return The authentication request sent by an origin server to a client.
*/
public ChallengeRequest getChallengeRequest() {
return this.challengeRequest;
}
/**
* Returns the cookie settings provided by the server.
*
* @return The cookie settings provided by the server.
*/
public List<CookieSetting> getCookieSettings() {
if (this.cookieSettings == null)
this.cookieSettings = new ArrayList<CookieSetting>();
return this.cookieSettings;
}
/**
* Returns the set of selecting dimensions on which the response entity may
* vary. If some server-side content negotiation is done, this set should be
* properly updated, other it can be left empty.
*
* @return The set of dimensions on which the response entity may vary.
*/
public Set<Dimension> getDimensions() {
if (this.dimensions == null)
this.dimensions = EnumSet.noneOf(Dimension.class);
return this.dimensions;
}
/**
* Returns the reference that the client should follow for redirections or
* resource creations.
*
* @return The redirection reference.
*/
public Reference getRedirectRef() {
return this.redirectRef;
}
/**
* Returns the associated request
*
* @return The associated request
*/
public Request getRequest() {
return request;
}
/**
* Returns the server-specific information.
*
* @return The server-specific information.
*/
public ServerInfo getServerInfo() {
if (this.serverInfo == null)
this.serverInfo = new ServerInfo();
return this.serverInfo;
}
/**
* Returns the status.
*
* @return The status.
*/
public Status getStatus() {
return this.status;
}
/**
* Permanently redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetUri
* The target URI.
*/
public void redirectPermanent(String targetUri) {
redirectPermanent(new Reference(targetUri));
}
/**
* Permanently redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetRef
* The target URI reference.
*/
public void redirectPermanent(Reference targetRef) {
setRedirectRef(targetRef);
setStatus(Status.REDIRECTION_PERMANENT);
}
/**
* Redirects the client to a different URI that SHOULD be retrieved using a
* GET method on that resource. This method exists primarily to allow the
* output of a POST-activated script to redirect the user agent to a
* selected resource. The new URI is not a substitute reference for the
* originally requested resource.
*
* @param targetUri
* The target URI.
*/
public void redirectSeeOther(String targetUri) {
redirectSeeOther(new Reference(targetUri));
}
/**
* Redirects the client to a different URI that SHOULD be retrieved using a
* GET method on that resource. This method exists primarily to allow the
* output of a POST-activated script to redirect the user agent to a
* selected resource. The new URI is not a substitute reference for the
* originally requested resource.
*
* @param targetRef
* The target reference.
*/
public void redirectSeeOther(Reference targetRef) {
setRedirectRef(targetRef);
setStatus(Status.REDIRECTION_SEE_OTHER);
}
/**
* Temporarily redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetUri
* The target URI.
*/
public void redirectTemporary(String targetUri) {
redirectTemporary(new Reference(targetUri));
}
/**
* Temporarily redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetRef
* The target reference.
*/
public void redirectTemporary(Reference targetRef) {
setRedirectRef(targetRef);
setStatus(Status.REDIRECTION_TEMPORARY);
}
/**
* Sets the authentication request sent by an origin server to a client.
*
* @param request
* The authentication request sent by an origin server to a
* client.
*/
public void setChallengeRequest(ChallengeRequest request) {
this.challengeRequest = request;
}
/**
* Sets the entity representation. If the current status is SUCCESS_OK and
* the request conditions are matched, then the status is set to
* REDIRECTION_NOT_MODIFIED. In all other cases, the status is untouched and
* the entity is simply set.
*
* @param entity
* The entity representation.
*/
public void setEntity(Representation entity) {
if (getStatus().equals(Status.SUCCESS_OK)) {
if (getRequest().getConditions().isModified(entity)) {
// Send the representation as the response entity
super.setEntity(entity);
} else {
// Indicates to the client that he already has the best
// representation
setStatus(Status.REDIRECTION_NOT_MODIFIED);
}
} else {
super.setEntity(entity);
}
}
/**
* Sets the entity with the preferred representation of a resource,
* according to the client preferences. <br/> If no representation is found,
* sets the status to "Not found".<br/> If no acceptable representation is
* available, sets the status to "Not acceptable".<br/>
*
* @param resource
* The resource for which the best representation needs to be
* set.
* @see <a
* href="http://httpd.apache.org/docs/2.2/en/content-negotiation.html#algorithm">Apache
* content negotiation algorithm</a>
*/
public void setEntity(Resource resource) {
List<Representation> variants = resource.getVariants();
if ((variants == null) || (variants.size() < 1)) {
// Resource not found
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Compute the preferred variant
Representation preferredVariant = getRequest().getClientInfo()
.getPreferredVariant(variants);
// Update the variant dimensions used for content negotiation
getDimensions().add(Dimension.CHARACTER_SET);
getDimensions().add(Dimension.ENCODING);
getDimensions().add(Dimension.LANGUAGE);
getDimensions().add(Dimension.MEDIA_TYPE);
if (preferredVariant == null) {
// No variant was found matching the client preferences
setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
+ // The list of all variants is transmitted to the client
+ ReferenceList refs = new ReferenceList(variants.size());
+ for (Representation variant : variants) {
+ if (variant.getIdentifier() != null) {
+ refs.add(variant.getIdentifier());
+ }
+ }
+ this.setEntity(refs.getTextRepresentation());
} else {
setEntity(preferredVariant);
}
}
}
/**
* Sets the reference that the client should follow for redirections or
* resource creations.
*
* @param redirectRef
* The redirection reference.
*/
public void setRedirectRef(Reference redirectRef) {
this.redirectRef = redirectRef;
}
/**
* Sets the reference that the client should follow for redirections or
* resource creations.
*
* @param redirectUri
* The redirection URI.
*/
public void setRedirectRef(String redirectUri) {
Reference baseRef = (getRequest().getResourceRef() != null) ? getRequest()
.getResourceRef().getBaseRef()
: null;
setRedirectRef(new Reference(baseRef, redirectUri).getTargetRef());
}
/**
* Sets the associated request.
*
* @param request
* The associated request
*/
public void setRequest(Request request) {
this.request = request;
}
/**
* Sets the status.
*
* @param status
* The status to set.
*/
public void setStatus(Status status) {
this.status = status;
}
/**
* Sets the status.
*
* @param status
* The status to set.
* @param message
* The status message.
*/
public void setStatus(Status status, String message) {
setStatus(new Status(status, message));
}
}
| true | true |
public void setEntity(Resource resource) {
List<Representation> variants = resource.getVariants();
if ((variants == null) || (variants.size() < 1)) {
// Resource not found
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Compute the preferred variant
Representation preferredVariant = getRequest().getClientInfo()
.getPreferredVariant(variants);
// Update the variant dimensions used for content negotiation
getDimensions().add(Dimension.CHARACTER_SET);
getDimensions().add(Dimension.ENCODING);
getDimensions().add(Dimension.LANGUAGE);
getDimensions().add(Dimension.MEDIA_TYPE);
if (preferredVariant == null) {
// No variant was found matching the client preferences
setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
} else {
setEntity(preferredVariant);
}
}
}
|
public void setEntity(Resource resource) {
List<Representation> variants = resource.getVariants();
if ((variants == null) || (variants.size() < 1)) {
// Resource not found
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Compute the preferred variant
Representation preferredVariant = getRequest().getClientInfo()
.getPreferredVariant(variants);
// Update the variant dimensions used for content negotiation
getDimensions().add(Dimension.CHARACTER_SET);
getDimensions().add(Dimension.ENCODING);
getDimensions().add(Dimension.LANGUAGE);
getDimensions().add(Dimension.MEDIA_TYPE);
if (preferredVariant == null) {
// No variant was found matching the client preferences
setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
// The list of all variants is transmitted to the client
ReferenceList refs = new ReferenceList(variants.size());
for (Representation variant : variants) {
if (variant.getIdentifier() != null) {
refs.add(variant.getIdentifier());
}
}
this.setEntity(refs.getTextRepresentation());
} else {
setEntity(preferredVariant);
}
}
}
|
diff --git a/src/payStation/gui/PayStationGUI.java b/src/payStation/gui/PayStationGUI.java
index 992543c..fff333b 100644
--- a/src/payStation/gui/PayStationGUI.java
+++ b/src/payStation/gui/PayStationGUI.java
@@ -1,171 +1,172 @@
package payStation.gui;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import payStation.payStationInterface.*;
import payStation.payStationInterface.exception.IllegalCoinException;
import payStation.impl.*;
/**
* Most of this is automatically created by WindowBuilder in Eclipse
*/
public class PayStationGUI {
private JFrame frmPayStation;
private JTextField coinInputTextField;
private JLabel centLabel;
private JLabel minutesLabel;
private PayStation payStation = new PayStationImpl();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PayStationGUI window = new PayStationGUI();
window.frmPayStation.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PayStationGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPayStation = new JFrame();
frmPayStation.setTitle("Pay Station");
frmPayStation.setBounds(100, 100, 419, 194);
frmPayStation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPayStation.getContentPane().setLayout(
new MigLayout("", "[][][][][][][grow][][]", "[][][][][]"));
Component horizontalStrut = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut, "cell 3 0");
Component horizontalStrut_2 = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut_2, "cell 5 0");
JLabel lblYouHavePaid = new JLabel("You have paid:");
frmPayStation.getContentPane().add(lblYouHavePaid, "cell 1 1");
centLabel = new JLabel("0");
frmPayStation.getContentPane().add(centLabel, "cell 3 1");
JLabel lblCents = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents, "cell 4 1");
JLabel lblInsertCoin = new JLabel("Insert coin");
lblInsertCoin.setFont(new Font("Tahoma", Font.BOLD, 11));
frmPayStation.getContentPane().add(lblInsertCoin,
"cell 6 1,alignx center");
JLabel lblYouHavePaid_1 = new JLabel("Your parking time:");
frmPayStation.getContentPane().add(lblYouHavePaid_1, "cell 1 2");
minutesLabel = new JLabel("0");
frmPayStation.getContentPane().add(minutesLabel, "cell 3 2");
JLabel lblMinutes = new JLabel("minutes");
frmPayStation.getContentPane().add(lblMinutes, "cell 4 2");
coinInputTextField = new JTextField();
coinInputTextField.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When enter is pressed after a number has been
* input, we try to get the number and send it to the payStation. If
* the coin is deemed invalid by the pay station, an
* IllegalCoinException is thrown
*/
public void actionPerformed(ActionEvent arg0) {
try {
int coinValue;
coinValue = Integer.parseInt(coinInputTextField.getText());
coinInputTextField.setText(null);
payStation.addPayment(coinValue);
updateLabels();
} catch (NumberFormatException ex) {
// User entered something other than a number, do nothing
} catch (IllegalCoinException ex) {
- JOptionPane.showInternalMessageDialog(frmPayStation,
+ JOptionPane.showInternalMessageDialog(
+ frmPayStation.getContentPane(),
"Invalid coin inserted: coin returned",
"Invalid coin", JOptionPane.INFORMATION_MESSAGE);
}
}
});
frmPayStation.getContentPane()
.add(coinInputTextField, "cell 6 2,growx");
coinInputTextField.setColumns(10);
JLabel lblCents_1 = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents_1, "cell 7 2,alignx left");
Component horizontalStrut_1 = Box.createHorizontalStrut(20);
frmPayStation.getContentPane().add(horizontalStrut_1, "cell 8 2");
JButton buyButton = new JButton("Buy");
buyButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the buy button is clicked, we request a
* receipt from the payStation and display it
*/
public void actionPerformed(ActionEvent arg0) {
Receipt receipt = payStation.buy();
updateLabels();
JOptionPane.showInternalMessageDialog(
frmPayStation.getContentPane(),
"Payment: " + receipt.getPayment() + "\nParking Time: "
+ receipt.getMinutes(), "Receipt",
JOptionPane.INFORMATION_MESSAGE);
}
});
frmPayStation.getContentPane().add(buyButton, "cell 1 4");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the cancel button is pressed, the payStation
* is reset and the labels are updated
*/
public void actionPerformed(ActionEvent arg0) {
payStation.cancel();
updateLabels();
}
});
frmPayStation.getContentPane().add(cancelButton, "cell 2 4 3 1");
}
/**
* Updates the cent and the minutes labels with their current value in
* payStation
*/
private void updateLabels() {
centLabel.setText(Integer.toString(payStation.getPayment()));
minutesLabel.setText(Integer.toString(payStation.getMinutes()));
}
}
| true | true |
private void initialize() {
frmPayStation = new JFrame();
frmPayStation.setTitle("Pay Station");
frmPayStation.setBounds(100, 100, 419, 194);
frmPayStation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPayStation.getContentPane().setLayout(
new MigLayout("", "[][][][][][][grow][][]", "[][][][][]"));
Component horizontalStrut = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut, "cell 3 0");
Component horizontalStrut_2 = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut_2, "cell 5 0");
JLabel lblYouHavePaid = new JLabel("You have paid:");
frmPayStation.getContentPane().add(lblYouHavePaid, "cell 1 1");
centLabel = new JLabel("0");
frmPayStation.getContentPane().add(centLabel, "cell 3 1");
JLabel lblCents = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents, "cell 4 1");
JLabel lblInsertCoin = new JLabel("Insert coin");
lblInsertCoin.setFont(new Font("Tahoma", Font.BOLD, 11));
frmPayStation.getContentPane().add(lblInsertCoin,
"cell 6 1,alignx center");
JLabel lblYouHavePaid_1 = new JLabel("Your parking time:");
frmPayStation.getContentPane().add(lblYouHavePaid_1, "cell 1 2");
minutesLabel = new JLabel("0");
frmPayStation.getContentPane().add(minutesLabel, "cell 3 2");
JLabel lblMinutes = new JLabel("minutes");
frmPayStation.getContentPane().add(lblMinutes, "cell 4 2");
coinInputTextField = new JTextField();
coinInputTextField.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When enter is pressed after a number has been
* input, we try to get the number and send it to the payStation. If
* the coin is deemed invalid by the pay station, an
* IllegalCoinException is thrown
*/
public void actionPerformed(ActionEvent arg0) {
try {
int coinValue;
coinValue = Integer.parseInt(coinInputTextField.getText());
coinInputTextField.setText(null);
payStation.addPayment(coinValue);
updateLabels();
} catch (NumberFormatException ex) {
// User entered something other than a number, do nothing
} catch (IllegalCoinException ex) {
JOptionPane.showInternalMessageDialog(frmPayStation,
"Invalid coin inserted: coin returned",
"Invalid coin", JOptionPane.INFORMATION_MESSAGE);
}
}
});
frmPayStation.getContentPane()
.add(coinInputTextField, "cell 6 2,growx");
coinInputTextField.setColumns(10);
JLabel lblCents_1 = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents_1, "cell 7 2,alignx left");
Component horizontalStrut_1 = Box.createHorizontalStrut(20);
frmPayStation.getContentPane().add(horizontalStrut_1, "cell 8 2");
JButton buyButton = new JButton("Buy");
buyButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the buy button is clicked, we request a
* receipt from the payStation and display it
*/
public void actionPerformed(ActionEvent arg0) {
Receipt receipt = payStation.buy();
updateLabels();
JOptionPane.showInternalMessageDialog(
frmPayStation.getContentPane(),
"Payment: " + receipt.getPayment() + "\nParking Time: "
+ receipt.getMinutes(), "Receipt",
JOptionPane.INFORMATION_MESSAGE);
}
});
frmPayStation.getContentPane().add(buyButton, "cell 1 4");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the cancel button is pressed, the payStation
* is reset and the labels are updated
*/
public void actionPerformed(ActionEvent arg0) {
payStation.cancel();
updateLabels();
}
});
frmPayStation.getContentPane().add(cancelButton, "cell 2 4 3 1");
}
|
private void initialize() {
frmPayStation = new JFrame();
frmPayStation.setTitle("Pay Station");
frmPayStation.setBounds(100, 100, 419, 194);
frmPayStation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPayStation.getContentPane().setLayout(
new MigLayout("", "[][][][][][][grow][][]", "[][][][][]"));
Component horizontalStrut = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut, "cell 3 0");
Component horizontalStrut_2 = Box.createHorizontalStrut(30);
frmPayStation.getContentPane().add(horizontalStrut_2, "cell 5 0");
JLabel lblYouHavePaid = new JLabel("You have paid:");
frmPayStation.getContentPane().add(lblYouHavePaid, "cell 1 1");
centLabel = new JLabel("0");
frmPayStation.getContentPane().add(centLabel, "cell 3 1");
JLabel lblCents = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents, "cell 4 1");
JLabel lblInsertCoin = new JLabel("Insert coin");
lblInsertCoin.setFont(new Font("Tahoma", Font.BOLD, 11));
frmPayStation.getContentPane().add(lblInsertCoin,
"cell 6 1,alignx center");
JLabel lblYouHavePaid_1 = new JLabel("Your parking time:");
frmPayStation.getContentPane().add(lblYouHavePaid_1, "cell 1 2");
minutesLabel = new JLabel("0");
frmPayStation.getContentPane().add(minutesLabel, "cell 3 2");
JLabel lblMinutes = new JLabel("minutes");
frmPayStation.getContentPane().add(lblMinutes, "cell 4 2");
coinInputTextField = new JTextField();
coinInputTextField.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When enter is pressed after a number has been
* input, we try to get the number and send it to the payStation. If
* the coin is deemed invalid by the pay station, an
* IllegalCoinException is thrown
*/
public void actionPerformed(ActionEvent arg0) {
try {
int coinValue;
coinValue = Integer.parseInt(coinInputTextField.getText());
coinInputTextField.setText(null);
payStation.addPayment(coinValue);
updateLabels();
} catch (NumberFormatException ex) {
// User entered something other than a number, do nothing
} catch (IllegalCoinException ex) {
JOptionPane.showInternalMessageDialog(
frmPayStation.getContentPane(),
"Invalid coin inserted: coin returned",
"Invalid coin", JOptionPane.INFORMATION_MESSAGE);
}
}
});
frmPayStation.getContentPane()
.add(coinInputTextField, "cell 6 2,growx");
coinInputTextField.setColumns(10);
JLabel lblCents_1 = new JLabel("cent");
frmPayStation.getContentPane().add(lblCents_1, "cell 7 2,alignx left");
Component horizontalStrut_1 = Box.createHorizontalStrut(20);
frmPayStation.getContentPane().add(horizontalStrut_1, "cell 8 2");
JButton buyButton = new JButton("Buy");
buyButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the buy button is clicked, we request a
* receipt from the payStation and display it
*/
public void actionPerformed(ActionEvent arg0) {
Receipt receipt = payStation.buy();
updateLabels();
JOptionPane.showInternalMessageDialog(
frmPayStation.getContentPane(),
"Payment: " + receipt.getPayment() + "\nParking Time: "
+ receipt.getMinutes(), "Receipt",
JOptionPane.INFORMATION_MESSAGE);
}
});
frmPayStation.getContentPane().add(buyButton, "cell 1 4");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
/*
* (non-Javadoc) When the cancel button is pressed, the payStation
* is reset and the labels are updated
*/
public void actionPerformed(ActionEvent arg0) {
payStation.cancel();
updateLabels();
}
});
frmPayStation.getContentPane().add(cancelButton, "cell 2 4 3 1");
}
|
diff --git a/src/com/jidesoft/swing/ComboBoxSearchable.java b/src/com/jidesoft/swing/ComboBoxSearchable.java
index 0ab6fc2c..9ae30ef9 100644
--- a/src/com/jidesoft/swing/ComboBoxSearchable.java
+++ b/src/com/jidesoft/swing/ComboBoxSearchable.java
@@ -1,277 +1,275 @@
/*
* @(#)${NAME}
*
* Copyright 2002 - 2004 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import com.jidesoft.swing.event.SearchableEvent;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* <code>ComboBoxSearchable</code> is an concrete implementation of {@link Searchable} that enables the search function
* in non-editable JComboBox. <p>It's very simple to use it. Assuming you have a JComboBox, all you need to do is to
* call
* <code><pre>
* JComboBox comboBox = ....;
* ComboBoxSearchable searchable = new ComboBoxSearchable(comboBox);
* </pre></code>
* Now the JComboBox will have the search function.
* <p/>
* There is very little customization you need to do to ComboBoxSearchable. The only thing you might need is when the
* element in the JComboBox needs a special conversion to convert to string. If so, you can override
* convertElementToString() to provide you own algorithm to do the conversion.
* <code><pre>
* JComboBox comboBox = ....;
* ComboBoxSearchable searchable = new ComboBoxSearchable(comboBox) {
* protected String convertElementToString(Object object) {
* ...
* }
* };
* </pre></code>
* <p/>
* Additional customization can be done on the base Searchable class such as background and foreground color,
* keystrokes, case sensitivity,
*/
public class ComboBoxSearchable extends Searchable implements ListDataListener, PropertyChangeListener, PopupMenuListener {
private boolean _refreshPopupDuringSearching = false;
private boolean _showPopupDuringSearching = true;
public ComboBoxSearchable(final JComboBox comboBox) {
super(comboBox);
// to avoid conflict with default type-match feature of JComboBox.
comboBox.setKeySelectionManager(new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1;
}
});
comboBox.getModel().addListDataListener(this);
comboBox.addPropertyChangeListener("model", this);
comboBox.addPopupMenuListener(this);
if (comboBox.isEditable()) {
Component editorComponent = comboBox.getEditor().getEditorComponent();
final JTextField textField = (JTextField) editorComponent;
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED && e.getKeyCode() != KeyEvent.VK_ENTER
&& e.getKeyCode() != KeyEvent.VK_ESCAPE) {
String text = textField.getText();
ComboBoxModel model = comboBox.getModel();
ListDataListener removedListener = null;
// this is a hack. We have to remove the listener registered in BasicComboBoxUI while filtering the combobox model.
// the code below will break if the listener is not a class in BasicComboBoxUI.
if (model instanceof AbstractListModel) {
ListDataListener[] listeners = ((AbstractListModel) model).getListDataListeners();
for (ListDataListener listener : listeners) {
//noinspection IndexOfReplaceableByContains
if (listener.getClass().toString().indexOf("BasicComboBoxUI") != -1) {
removedListener = listener;
model.removeListDataListener(listener);
}
}
}
textChanged(text);
if (removedListener != null) {
model.addListDataListener(removedListener);
}
- if (!comboBox.isPopupVisible()) {
- comboBox.showPopup();
- }
+ comboBox.showPopup();
}
}
});
setSearchableProvider(new SearchableProvider() {
@Override
public String getSearchingText() {
return textField.getText();
}
@Override
public boolean isPassive() {
return true;
}
@Override
public void processKeyEvent(KeyEvent e) {
}
});
}
}
@Override
public void uninstallListeners() {
super.uninstallListeners();
if (_component instanceof JComboBox) {
((JComboBox) _component).getModel().removeListDataListener(this);
((JComboBox) _component).removePopupMenuListener(this);
}
_component.removePropertyChangeListener("model", this);
}
/**
* Checks if the popup is showing during searching.
*
* @return true if popup is visible during searching.
*/
public boolean isShowPopupDuringSearching() {
return _showPopupDuringSearching;
}
/**
* Sets the property which determines if the popup should be shown during searching.
*
* @param showPopupDuringSearching the flag indicating if we should show popup during searching
*/
public void setShowPopupDuringSearching(boolean showPopupDuringSearching) {
_showPopupDuringSearching = showPopupDuringSearching;
}
/**
* Checks if the popup should be refreshed during searching.
* <p/>
* By default, the value is false. ComboBoxShrinkSearchSupport will set this flag to true.
*
* @return true if popup is refreshed during searching.
*/
public boolean isRefreshPopupDuringSearching() {
return _refreshPopupDuringSearching;
}
/**
* Sets the property which determines if the popup should be refreshed during searching.
*
* @param refreshPopupDuringSearching the flag indicating if we should refresh popup during searching
*/
public void setRefreshPopupDuringSearching(boolean refreshPopupDuringSearching) {
_refreshPopupDuringSearching = refreshPopupDuringSearching;
}
@Override
protected void setSelectedIndex(int index, boolean incremental) {
if (((JComboBox) _component).getSelectedIndex() != index) {
((JComboBox) _component).setSelectedIndex(index);
}
if (isRefreshPopupDuringSearching()) {
boolean old = isHideSearchPopupOnEvent();
setHideSearchPopupOnEvent(false);
((JComboBox) _component).hidePopup();
setHideSearchPopupOnEvent(old);
}
if (isShowPopupDuringSearching() || isRefreshPopupDuringSearching()) {
try {
if (!((JComboBox) _component).isPopupVisible() &&
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() != null &&
SwingUtilities.isDescendingFrom(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(), _component)) {
((JComboBox) _component).showPopup();
}
}
catch (IllegalComponentStateException e) {
//null
}
}
}
@Override
protected int getSelectedIndex() {
return ((JComboBox) _component).getSelectedIndex();
}
@Override
protected Object getElementAt(int index) {
ComboBoxModel comboBoxModel = ((JComboBox) _component).getModel();
return comboBoxModel.getElementAt(index);
}
@Override
protected int getElementCount() {
ComboBoxModel comboBoxModel = ((JComboBox) _component).getModel();
return comboBoxModel.getSize();
}
/**
* Converts the element in JCombobox to string. The returned value will be the <code>toString()</code> of whatever
* element that returned from <code>list.getModel().getElementAt(i)</code>.
*
* @param object the object to be converted
*
* @return the string representing the element in the JComboBox.
*/
@Override
protected String convertElementToString(Object object) {
if (object != null) {
return object.toString();
}
else {
return "";
}
}
public void contentsChanged(ListDataEvent e) {
if (!isProcessModelChangeEvent()) {
return;
}
if (e.getIndex0() == -1 && e.getIndex1() == -1) {
}
else {
hidePopup();
fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE));
}
}
public void intervalAdded(ListDataEvent e) {
if (!isProcessModelChangeEvent()) {
return;
}
hidePopup();
fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE));
}
public void intervalRemoved(ListDataEvent e) {
if (!isProcessModelChangeEvent()) {
return;
}
hidePopup();
fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE));
}
public void propertyChange(PropertyChangeEvent evt) {
if ("model".equals(evt.getPropertyName())) {
hidePopup();
if (evt.getOldValue() instanceof ComboBoxModel) {
((ComboBoxModel) evt.getOldValue()).removeListDataListener(this);
}
if (evt.getNewValue() instanceof ComboBoxModel) {
((ComboBoxModel) evt.getNewValue()).addListDataListener(this);
}
fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE));
}
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
if (isHideSearchPopupOnEvent()) {
hidePopup();
}
}
public void popupMenuCanceled(PopupMenuEvent e) {
}
}
| true | true |
public ComboBoxSearchable(final JComboBox comboBox) {
super(comboBox);
// to avoid conflict with default type-match feature of JComboBox.
comboBox.setKeySelectionManager(new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1;
}
});
comboBox.getModel().addListDataListener(this);
comboBox.addPropertyChangeListener("model", this);
comboBox.addPopupMenuListener(this);
if (comboBox.isEditable()) {
Component editorComponent = comboBox.getEditor().getEditorComponent();
final JTextField textField = (JTextField) editorComponent;
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED && e.getKeyCode() != KeyEvent.VK_ENTER
&& e.getKeyCode() != KeyEvent.VK_ESCAPE) {
String text = textField.getText();
ComboBoxModel model = comboBox.getModel();
ListDataListener removedListener = null;
// this is a hack. We have to remove the listener registered in BasicComboBoxUI while filtering the combobox model.
// the code below will break if the listener is not a class in BasicComboBoxUI.
if (model instanceof AbstractListModel) {
ListDataListener[] listeners = ((AbstractListModel) model).getListDataListeners();
for (ListDataListener listener : listeners) {
//noinspection IndexOfReplaceableByContains
if (listener.getClass().toString().indexOf("BasicComboBoxUI") != -1) {
removedListener = listener;
model.removeListDataListener(listener);
}
}
}
textChanged(text);
if (removedListener != null) {
model.addListDataListener(removedListener);
}
if (!comboBox.isPopupVisible()) {
comboBox.showPopup();
}
}
}
});
setSearchableProvider(new SearchableProvider() {
@Override
public String getSearchingText() {
return textField.getText();
}
@Override
public boolean isPassive() {
return true;
}
@Override
public void processKeyEvent(KeyEvent e) {
}
});
}
}
|
public ComboBoxSearchable(final JComboBox comboBox) {
super(comboBox);
// to avoid conflict with default type-match feature of JComboBox.
comboBox.setKeySelectionManager(new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1;
}
});
comboBox.getModel().addListDataListener(this);
comboBox.addPropertyChangeListener("model", this);
comboBox.addPopupMenuListener(this);
if (comboBox.isEditable()) {
Component editorComponent = comboBox.getEditor().getEditorComponent();
final JTextField textField = (JTextField) editorComponent;
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED && e.getKeyCode() != KeyEvent.VK_ENTER
&& e.getKeyCode() != KeyEvent.VK_ESCAPE) {
String text = textField.getText();
ComboBoxModel model = comboBox.getModel();
ListDataListener removedListener = null;
// this is a hack. We have to remove the listener registered in BasicComboBoxUI while filtering the combobox model.
// the code below will break if the listener is not a class in BasicComboBoxUI.
if (model instanceof AbstractListModel) {
ListDataListener[] listeners = ((AbstractListModel) model).getListDataListeners();
for (ListDataListener listener : listeners) {
//noinspection IndexOfReplaceableByContains
if (listener.getClass().toString().indexOf("BasicComboBoxUI") != -1) {
removedListener = listener;
model.removeListDataListener(listener);
}
}
}
textChanged(text);
if (removedListener != null) {
model.addListDataListener(removedListener);
}
comboBox.showPopup();
}
}
});
setSearchableProvider(new SearchableProvider() {
@Override
public String getSearchingText() {
return textField.getText();
}
@Override
public boolean isPassive() {
return true;
}
@Override
public void processKeyEvent(KeyEvent e) {
}
});
}
}
|
diff --git a/src/MultiAction.java b/src/MultiAction.java
index 8b7c24c..894e7c4 100644
--- a/src/MultiAction.java
+++ b/src/MultiAction.java
@@ -1,661 +1,666 @@
/*
* Copyright (C) 2010-2012 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Package-private class to batch multiple RPCs for a same region together.
* <p>
* This RPC is guaranteed to be sent atomically (but HBase doesn't guarantee
* that it will apply it atomically).
*/
final class MultiAction extends HBaseRpc {
// NOTE: I apologize for the long methods and complex control flow logic,
// with many nested loops and `if's. `multiPut' and `multi' have always
// been a gigantic mess in HBase, and despite my best efforts to provide
// a reasonable implementation, it's obvious that the resulting code is
// unwieldy. I originally wrote support for `multi' as a separate class
// from `multiPut', but this resulted in a lot of code duplication and
// added complexity in other places that had to deal with either kind of
// RPCs depending on the server version. Hence this class supports both
// RPCs, which does add a bit of complexity to the already unnecessarily
// complex logic. This was better than all the code duplication. And
// believe me, what's here is -- in my biased opinion -- significantly
// better than the insane spaghetti mess in HBase's client and server.
private static final byte[] MULTI_PUT = new byte[] {
'm', 'u', 'l', 't', 'i', 'P', 'u', 't'
};
private static final byte[] MULTI = new byte[] {
'm', 'u', 'l', 't', 'i'
};
/** Template for NSREs. */
private static final NotServingRegionException NSRE =
new NotServingRegionException("Region unavailable", null);
/**
* Protocol version from which we can use `multi' instead of `multiPut'.
* Technically we could use `multi' with HBase 0.90.x, but as explained
* in HBASE-5204, because of a change in HBASE-3335 this is harder than
* necessary, so we don't support it.
*/
static final byte USE_MULTI = RegionClient.SERVER_VERSION_092_OR_ABOVE;
/**
* All the RPCs in this batch.
* We'll sort this list before serializing it.
* @see MultiActionComparator
*/
private final ArrayList<BatchableRpc> batch = new ArrayList<BatchableRpc>();
/**
* Constructor.
*/
public MultiAction(final byte server_version) {
super(server_version >= USE_MULTI ? MULTI : MULTI_PUT);
}
/** Returns the number of RPCs in this batch. */
public int size() {
return batch.size();
}
/**
* Adds an RPC to this batch.
* <p>
* @param rpc The RPC to add in this batch.
* Any edit added <b>must not</b> specify an explicit row lock.
*/
public void add(final BatchableRpc rpc) {
if (rpc.lockid != RowLock.NO_LOCK) {
throw new AssertionError("Should never happen! We don't do multi-put"
+ " with RowLocks but we've been given an edit that has one!"
+ " edit=" + rpc + ", this=" + this);
}
batch.add(rpc);
}
/** Returns the list of individual RPCs that make up this batch. */
ArrayList<BatchableRpc> batch() {
return batch;
}
/**
* Predicts a lower bound on the serialized size of this RPC.
* This is to avoid using a dynamic buffer, to avoid re-sizing the buffer.
* Since we use a static buffer, if the prediction is wrong and turns out
* to be less than what we need, there will be an exception which will
* prevent the RPC from being serialized. That'd be a severe bug.
* @param server_version What RPC protocol version the server is running.
*/
private int predictSerializedSize(final byte server_version) {
// See the comment in serialize() about the for loop that follows.
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 1; // byte: Type again (see HBASE-2877).
size += 4; // int: How many regions do we want to affect?
// Are we serializing a `multi' RPC, or `multiPut'?
final boolean use_multi = method() == MULTI;
BatchableRpc prev = PutRequest.EMPTY_PUT;
for (final BatchableRpc rpc : batch) {
final byte[] region_name = rpc.getRegion().name();
final boolean new_region = !Bytes.equals(prev.getRegion().name(),
region_name);
final byte[] family = rpc.family();
final boolean new_key = (new_region
|| prev.code() != rpc.code()
|| !Bytes.equals(prev.key, rpc.key)
|| family == DeleteRequest.WHOLE_ROW);
final boolean new_family = new_key || !Bytes.equals(prev.family(),
family);
if (new_region) {
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region_name.length; // The region name.
size += 4; // int: How many RPCs for this region.
}
final int key_length = rpc.key.length;
if (new_key) {
if (use_multi) {
size += 4; // int: Number of "attributes" for the last key (none).
size += 4; // Index of this `action'.
size += 3; // 3 bytes to serialize `null'.
size += 1; // byte: Type code for `Action'.
size += 1; // byte: Type code again (see HBASE-2877).
size += 1; // byte: Code for a `Row' object.
size += 1; // byte: Code for a `Put' object.
}
size += 1; // byte: Version of Put.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key_length; // The row key.
size += 8; // long: Timestamp.
size += 8; // long: Lock ID.
size += 1; // bool: Whether or not to write to the WAL.
size += 4; // int: Number of families for which we have edits.
}
if (new_family) {
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
size += 4; // int: Number of KeyValues that follow.
if (rpc.code() == PutRequest.CODE) {
size += 4; // int: Total number of bytes for all those KeyValues.
}
}
size += rpc.payloadSize();
prev = rpc;
}
return size;
}
/** Serializes this request. */
ChannelBuffer serialize(final byte server_version) {
// Due to the wire format expected by HBase, we need to group all the
// edits by region, then by key, then by family. HBase does this by
// building a crazy map-of-map-of-map-of-list-of-edits, but this is
// memory and time inefficient (lots of unnecessary references and
// O(n log n) operations). The approach we take here is to sort the
// list and iterate on it. Each time we find a different family or
// row key or region, we start a new set of edits. Because the RPC
// format needs to know the number of edits or bytes that follows in
// various places, we store a "0" value and then later monkey-patch it
// once we cross a row key / family / region boundary, because we can't
// efficiently tell ahead of time how many edits or bytes will follow
// until we cross such boundaries.
Collections.sort(batch, MULTI_CMP);
final ChannelBuffer buf = newBuffer(server_version,
predictSerializedSize(server_version));
buf.writeInt(1); // Number of parameters.
// Are we serializing a `multi' RPC, or `multiPut'?
final boolean use_multi = method() == MULTI;
{ // 1st and only param.
final int code = use_multi ? 66 : 57; // `MultiAction' or `MultiPut'.
buf.writeByte(code); // Type code for the parameter.
buf.writeByte(code); // Type code again (see HBASE-2877).
}
buf.writeInt(0); // How many regions do we want to affect?
// ^------ We'll monkey patch this at the end.
int nregions = 0;
int nkeys_index = -1;
int nkeys = 0;
int nfamilies_index = -1;
int nfamilies = 0;
int nkeys_per_family_index = -1;
int nkeys_per_family = 0;
int nbytes_per_family = 0;
int nrpcs_per_key = 0;
BatchableRpc prev = PutRequest.EMPTY_PUT;
for (final BatchableRpc rpc : batch) {
final byte[] region_name = rpc.getRegion().name();
final boolean new_region = !Bytes.equals(prev.getRegion().name(),
region_name);
final byte[] family = rpc.family();
final boolean new_key = (new_region
|| prev.code() != rpc.code()
|| !Bytes.equals(prev.key, rpc.key)
|| family == DeleteRequest.WHOLE_ROW);
final boolean new_family = new_key || !Bytes.equals(prev.family(),
family);
if (new_key && use_multi && nkeys_index > 0) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing useless junk from `Action'. After serializing its
// `action' (which implements an interface awesomely named `Row'),
// HBase adds the index of the `action' as the server will sort
// actions by key. This is pretty useless as if the client was
// sorting things before sending them off to the server, like we
// do, then we wouldn't need to pass an index to be able to match
// up requests and responses. Since we don't need this index, we
// instead use this field for another purpose: remembering how
// many RPCs we sent for this particular key. This will help us
// when de-serializing the response.
buf.writeInt(nrpcs_per_key);
nrpcs_per_key = 0;
// Then, because an `Action' can also contain a result, the code
// also serializes that. Of course for us end-users, this is stupid
// because we never send a result along with our request.
writeHBaseNull(buf);
}
if (new_region) {
// Monkey-patch the number of edits of the previous region.
if (nkeys_index > 0) {
buf.setInt(nkeys_index, nkeys);
nkeys = 0;
}
nregions++;
writeByteArray(buf, region_name); // The region name.
nkeys_index = buf.writerIndex();
// Number of keys for which we have RPCs for this region.
buf.writeInt(0); // We'll monkey patch this later.
}
final byte[] key = rpc.key;
if (new_key) {
// Monkey-patch the number of families of the previous key.
if (nfamilies_index > 0) {
buf.setInt(nfamilies_index, nfamilies);
nfamilies = 0;
}
if (use_multi) {
// Serialize an `Action' for the RPCs on this row.
buf.writeByte(65); // Code for an `Action' object.
buf.writeByte(65); // Code again (see HBASE-2877).
// Inside the action, serialize a `Put' object.
buf.writeByte(64); // Code for a `Row' object.
buf.writeByte(rpc.code()); // Code this object.
}
nkeys++;
// Right now we only support batching puts. In the future this part
// of the code will have to change to also want to allow get/deletes.
// The follow serializes a `Put'.
buf.writeByte(rpc.version(server_version)); // Undocumented versioning.
writeByteArray(buf, key); // The row key.
// This timestamp is unused, only the KeyValue-level timestamp is
// used, except in one case: whole-row deletes. In that case only,
// this timestamp is used by the RegionServer to create per-family
// deletes for that row. See HRegion.prepareDelete() for more info.
buf.writeLong(rpc.timestamp); // Timestamp.
buf.writeLong(RowLock.NO_LOCK); // Lock ID.
buf.writeByte(rpc.durable ? 0x01 : 0x00); // Use the WAL?
nfamilies_index = buf.writerIndex();
// Number of families that follow.
buf.writeInt(0); // We'll monkey patch this later.
}
if (new_family) {
// Monkey-patch the number and size of edits for the previous family.
if (nkeys_per_family_index > 0) {
buf.setInt(nkeys_per_family_index, nkeys_per_family);
if (prev.code() == PutRequest.CODE) {
buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
}
nkeys_per_family = 0;
nbytes_per_family = 0;
}
if (family == DeleteRequest.WHOLE_ROW) {
prev = rpc; // Short circuit. We have no KeyValue to write.
continue; // So loop again directly.
}
nfamilies++;
writeByteArray(buf, family); // The column family.
nkeys_per_family_index = buf.writerIndex();
// Number of "KeyValues" that follow.
buf.writeInt(0); // We'll monkey patch this later.
if (rpc.code() == PutRequest.CODE) {
// Total number of bytes taken by those "KeyValues".
// This is completely useless and only done for `Put'.
buf.writeInt(0); // We'll monkey patch this later.
}
}
nkeys_per_family += rpc.numKeyValues();
nrpcs_per_key++;
nbytes_per_family += rpc.payloadSize();
rpc.serializePayload(buf);
prev = rpc;
} // Yay, we made it!
if (use_multi) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing junk for the last `Action'. See comment above.
buf.writeInt(nrpcs_per_key);
writeHBaseNull(buf); // Useless.
}
- // Monkey-patch everything for the last set of edits.
- buf.setInt(nkeys_per_family_index, nkeys_per_family);
- if (prev.code() == PutRequest.CODE) {
- buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
+ // Note: the only case where nkeys_per_family_index remained -1 throughout
+ // this whole ordeal is where we didn't have any KV to serialize because
+ // every RPC was a `DeleteRequest.WHOLE_ROW'.
+ if (nkeys_per_family_index > 0) {
+ // Monkey-patch everything for the last set of edits.
+ buf.setInt(nkeys_per_family_index, nkeys_per_family);
+ if (prev.code() == PutRequest.CODE) {
+ buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
+ }
}
buf.setInt(nfamilies_index, nfamilies);
buf.setInt(nkeys_index, nkeys);
// Monkey-patch the number of regions affected by this RPC.
int header_length = 4 + 4 + 2 + method().length;
if (server_version >= RegionClient.SERVER_VERSION_092_OR_ABOVE) {
header_length += 1 + 8 + 4;
}
buf.setInt(header_length + 4 + 1 + 1, nregions);
return buf;
}
public String toString() {
// Originally this was simply putting all the batch in the toString
// representation, but that's way too expensive when we have large
// batches. So instead we toString each RPC until we hit some
// hard-coded upper bound on how much data we're willing to put into
// the toString. If we have too many RPCs and hit that constant,
// we skip all the remaining ones until the last one, as it's often
// useful to see the last RPC added when debugging.
final StringBuilder buf = new StringBuilder();
buf.append("MultiAction(batch=[");
final int nrpcs = batch.size();
int i;
for (i = 0; i < nrpcs; i++) {
if (buf.length() >= 1024) {
break;
}
buf.append(batch.get(i)).append(", ");
}
if (i < nrpcs) {
if (i == nrpcs - 1) {
buf.append("... 1 RPC not shown])");
} else {
buf.append("... ").append(nrpcs - 1 - i)
.append(" RPCs not shown ..., ")
.append(batch.get(nrpcs - 1))
.append("])");
}
} else {
buf.setLength(buf.length() - 2); // Remove the last ", "
buf.append("])");
}
return buf.toString();
}
/**
* Sorts {@link BatchableRpc}s appropriately for the multi-put / multi-action RPC.
* We sort by region, row key, column family. No ordering is needed on the
* column qualifier or value.
*/
static final MultiActionComparator MULTI_CMP = new MultiActionComparator();
/** Sorts {@link BatchableRpc}s appropriately for the `multi' RPC. */
private static final class MultiActionComparator
implements Comparator<BatchableRpc> {
private MultiActionComparator() { // Can't instantiate outside of this class.
}
@Override
/**
* Compares two RPCs.
*/
public int compare(final BatchableRpc a, final BatchableRpc b) {
int d;
if ((d = Bytes.memcmp(a.getRegion().name(), b.getRegion().name())) != 0) {
return d;
} else if ((d = a.code() - b.code()) != 0) { // Sort by code before key.
// Note that DeleteRequest.code() < PutRequest.code() and this matters
// as the RegionServer processes deletes before puts, and we want to
// send RPCs in the same order as they will be processed.
return d;
} else if ((d = Bytes.memcmp(a.key, b.key)) != 0) {
return d;
}
return Bytes.memcmp(a.family(), b.family());
}
}
/**
* Response to a {@link MultiAction} RPC.
*/
final class Response {
/** Response for each Action that was in the batch, in the same order. */
private final Object[] resps;
/** Constructor. */
Response(final Object[] resps) {
assert resps.length == batch.size() : "Got " + resps.length
+ " responses but expected " + batch.size();
this.resps = resps;
}
/**
* Returns the result number #i embodied in this response.
* @throws IndexOutOfBoundsException if i is greater than batch.size()
*/
public Object result(final int i) {
return resps[i];
}
public String toString() {
return "MultiAction.Response(" + Arrays.toString(resps) + ')';
}
}
/**
* De-serializes the response to a {@link MultiAction} RPC.
* See HBase's {@code MultiResponse}.
*/
Response responseFromBuffer(final ChannelBuffer buf) {
switch (buf.readByte()) {
case 58:
return deserializeMultiPutResponse(buf);
case 67:
return deserializeMultiResponse(buf);
}
throw new NonRecoverableException("Couldn't de-serialize "
+ Bytes.pretty(buf));
}
/**
* De-serializes a {@code MultiResponse}.
* This is only used when talking to HBase 0.92 and above.
*/
Response deserializeMultiResponse(final ChannelBuffer buf) {
final int nregions = buf.readInt();
HBaseRpc.checkNonEmptyArrayLength(buf, nregions);
final Object[] resps = new Object[batch.size()];
int n = 0; // Index in `batch'.
for (int i = 0; i < nregions; i++) {
final byte[] region_name = HBaseRpc.readByteArray(buf);
final int nkeys = buf.readInt();
HBaseRpc.checkNonEmptyArrayLength(buf, nkeys);
for (int j = 0; j < nkeys; j++) {
final int nrpcs_per_key = buf.readInt();
boolean error = buf.readByte() != 0x00;
Object resp; // Response for the current region.
if (error) {
final HBaseException e = RegionClient.deserializeException(buf, null);
resp = e;
} else {
resp = RegionClient.deserializeObject(buf, this);
// A successful response to a `Put' will be an empty `Result'
// object, which we de-serialize as an empty `ArrayList'.
// There's no need to waste memory keeping these around.
if (resp instanceof ArrayList && ((ArrayList) resp).isEmpty()) {
resp = SUCCESS;
} else if (resp == null) {
// Awesomely, `null' is used to indicate all RPCs for this region
// have failed, and we're not told why. Most of the time, it will
// be an NSRE, so assume that. What were they thinking when they
// wrote that code in HBase? Seriously WTF.
resp = NSRE;
error = true;
}
}
if (error) {
final HBaseException e = (HBaseException) resp;
for (int k = 0; k < nrpcs_per_key; k++) {
// We need to "clone" the exception for each RPC, as each RPC that
// failed needs to have its own exception with a reference to the
// failed RPC. This makes significantly simplifies the callbacks
// that do error handling, as they can extract the RPC out of the
// exception. The downside is that we don't have a perfect way of
// cloning "e", so instead we just abuse its `make' factory method
// slightly to duplicate it. This mangles the message a bit, but
// that's mostly harmless.
resps[n + k] = e.make(e.getMessage(), batch.get(n + k));
}
} else {
for (int k = 0; k < nrpcs_per_key; k++) {
resps[n + k] = resp;
}
}
n += nrpcs_per_key;
}
}
return new Response(resps);
}
/**
* De-serializes a {@code MultiPutResponse}.
* This is only used when talking to old versions of HBase (pre 0.92).
*/
Response deserializeMultiPutResponse(final ChannelBuffer buf) {
final int nregions = buf.readInt();
HBaseRpc.checkNonEmptyArrayLength(buf, nregions);
final int nrpcs = batch.size();
final Object[] resps = new Object[nrpcs];
int n = 0; // Index in `batch'.
for (int i = 0; i < nregions; i++) {
final byte[] region_name = HBaseRpc.readByteArray(buf);
// Sanity check. Response should give us regions back in same order.
assert Bytes.equals(region_name, batch.get(n).getRegion().name())
: ("WTF? " + Bytes.pretty(region_name) + " != "
+ batch.get(n).getRegion().name());
final int failed = buf.readInt(); // Index of the first failed edit.
// Because of HBASE-2898, we don't know which RPCs exactly failed. We
// only now that for that region, the one at index `failed' wasn't
// successful, so we can only assume that the subsequent ones weren't
// either, and retry them. First we need to find out how many RPCs
// we originally had for this region.
int edits_per_region = n;
while (edits_per_region < nrpcs
&& Bytes.equals(region_name,
batch.get(edits_per_region).getRegion().name())) {
edits_per_region++;
}
edits_per_region -= n;
assert failed < edits_per_region : "WTF? Found more failed RPCs " + failed
+ " than sent " + edits_per_region + " to " + Bytes.pretty(region_name);
// If `failed == -1' then we now that nothing has failed. Otherwise, we
// have that RPCs in [n; n + failed - 1] have succeeded, and RPCs in
// [n + failed; n + edits_per_region] have failed.
if (failed == -1) { // Fast-path for the case with no failures.
for (int j = 0; j < edits_per_region; j++) {
resps[n + j] = SUCCESS;
}
} else { // We had some failures.
assert failed >= 0 : "WTF? Found a negative failure index " + failed
+ " for region " + Bytes.pretty(region_name);
for (int j = 0; j < failed; j++) {
resps[n + j] = SUCCESS;
}
final String msg = "Multi-put failed on RPC #" + failed + "/"
+ edits_per_region + " on region " + Bytes.pretty(region_name);
for (int j = failed; j < edits_per_region; j++) {
resps[n + j] = new MultiPutFailedException(msg, batch.get(n + j));
}
}
n += edits_per_region;
}
return new Response(resps);
}
/**
* Used to represent the partial failure of a multi-put exception.
* This is only used with older versions of HBase (pre 0.92).
*/
private final class MultiPutFailedException extends RecoverableException
implements HasFailedRpcException {
final HBaseRpc failed_rpc;
/**
* Constructor.
* @param msg The message of the exception.
* @param failed_rpc The RPC that caused this exception.
*/
MultiPutFailedException(final String msg, final HBaseRpc failed_rpc) {
super(msg);
this.failed_rpc = failed_rpc;
}
@Override
public String getMessage() {
return super.getMessage() + "\nCaused by RPC: " + failed_rpc;
}
public HBaseRpc getFailedRpc() {
return failed_rpc;
}
@Override
MultiPutFailedException make(final Object msg, final HBaseRpc rpc) {
return new MultiPutFailedException(msg.toString(), rpc);
}
private static final long serialVersionUID = 1326900942;
}
/** Singleton class returned to indicate success of a multi-put. */
private static final class MultiActionSuccess {
private MultiActionSuccess() {
}
public String toString() {
return "MultiActionSuccess";
}
}
private static final MultiActionSuccess SUCCESS = new MultiActionSuccess();
}
| true | true |
ChannelBuffer serialize(final byte server_version) {
// Due to the wire format expected by HBase, we need to group all the
// edits by region, then by key, then by family. HBase does this by
// building a crazy map-of-map-of-map-of-list-of-edits, but this is
// memory and time inefficient (lots of unnecessary references and
// O(n log n) operations). The approach we take here is to sort the
// list and iterate on it. Each time we find a different family or
// row key or region, we start a new set of edits. Because the RPC
// format needs to know the number of edits or bytes that follows in
// various places, we store a "0" value and then later monkey-patch it
// once we cross a row key / family / region boundary, because we can't
// efficiently tell ahead of time how many edits or bytes will follow
// until we cross such boundaries.
Collections.sort(batch, MULTI_CMP);
final ChannelBuffer buf = newBuffer(server_version,
predictSerializedSize(server_version));
buf.writeInt(1); // Number of parameters.
// Are we serializing a `multi' RPC, or `multiPut'?
final boolean use_multi = method() == MULTI;
{ // 1st and only param.
final int code = use_multi ? 66 : 57; // `MultiAction' or `MultiPut'.
buf.writeByte(code); // Type code for the parameter.
buf.writeByte(code); // Type code again (see HBASE-2877).
}
buf.writeInt(0); // How many regions do we want to affect?
// ^------ We'll monkey patch this at the end.
int nregions = 0;
int nkeys_index = -1;
int nkeys = 0;
int nfamilies_index = -1;
int nfamilies = 0;
int nkeys_per_family_index = -1;
int nkeys_per_family = 0;
int nbytes_per_family = 0;
int nrpcs_per_key = 0;
BatchableRpc prev = PutRequest.EMPTY_PUT;
for (final BatchableRpc rpc : batch) {
final byte[] region_name = rpc.getRegion().name();
final boolean new_region = !Bytes.equals(prev.getRegion().name(),
region_name);
final byte[] family = rpc.family();
final boolean new_key = (new_region
|| prev.code() != rpc.code()
|| !Bytes.equals(prev.key, rpc.key)
|| family == DeleteRequest.WHOLE_ROW);
final boolean new_family = new_key || !Bytes.equals(prev.family(),
family);
if (new_key && use_multi && nkeys_index > 0) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing useless junk from `Action'. After serializing its
// `action' (which implements an interface awesomely named `Row'),
// HBase adds the index of the `action' as the server will sort
// actions by key. This is pretty useless as if the client was
// sorting things before sending them off to the server, like we
// do, then we wouldn't need to pass an index to be able to match
// up requests and responses. Since we don't need this index, we
// instead use this field for another purpose: remembering how
// many RPCs we sent for this particular key. This will help us
// when de-serializing the response.
buf.writeInt(nrpcs_per_key);
nrpcs_per_key = 0;
// Then, because an `Action' can also contain a result, the code
// also serializes that. Of course for us end-users, this is stupid
// because we never send a result along with our request.
writeHBaseNull(buf);
}
if (new_region) {
// Monkey-patch the number of edits of the previous region.
if (nkeys_index > 0) {
buf.setInt(nkeys_index, nkeys);
nkeys = 0;
}
nregions++;
writeByteArray(buf, region_name); // The region name.
nkeys_index = buf.writerIndex();
// Number of keys for which we have RPCs for this region.
buf.writeInt(0); // We'll monkey patch this later.
}
final byte[] key = rpc.key;
if (new_key) {
// Monkey-patch the number of families of the previous key.
if (nfamilies_index > 0) {
buf.setInt(nfamilies_index, nfamilies);
nfamilies = 0;
}
if (use_multi) {
// Serialize an `Action' for the RPCs on this row.
buf.writeByte(65); // Code for an `Action' object.
buf.writeByte(65); // Code again (see HBASE-2877).
// Inside the action, serialize a `Put' object.
buf.writeByte(64); // Code for a `Row' object.
buf.writeByte(rpc.code()); // Code this object.
}
nkeys++;
// Right now we only support batching puts. In the future this part
// of the code will have to change to also want to allow get/deletes.
// The follow serializes a `Put'.
buf.writeByte(rpc.version(server_version)); // Undocumented versioning.
writeByteArray(buf, key); // The row key.
// This timestamp is unused, only the KeyValue-level timestamp is
// used, except in one case: whole-row deletes. In that case only,
// this timestamp is used by the RegionServer to create per-family
// deletes for that row. See HRegion.prepareDelete() for more info.
buf.writeLong(rpc.timestamp); // Timestamp.
buf.writeLong(RowLock.NO_LOCK); // Lock ID.
buf.writeByte(rpc.durable ? 0x01 : 0x00); // Use the WAL?
nfamilies_index = buf.writerIndex();
// Number of families that follow.
buf.writeInt(0); // We'll monkey patch this later.
}
if (new_family) {
// Monkey-patch the number and size of edits for the previous family.
if (nkeys_per_family_index > 0) {
buf.setInt(nkeys_per_family_index, nkeys_per_family);
if (prev.code() == PutRequest.CODE) {
buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
}
nkeys_per_family = 0;
nbytes_per_family = 0;
}
if (family == DeleteRequest.WHOLE_ROW) {
prev = rpc; // Short circuit. We have no KeyValue to write.
continue; // So loop again directly.
}
nfamilies++;
writeByteArray(buf, family); // The column family.
nkeys_per_family_index = buf.writerIndex();
// Number of "KeyValues" that follow.
buf.writeInt(0); // We'll monkey patch this later.
if (rpc.code() == PutRequest.CODE) {
// Total number of bytes taken by those "KeyValues".
// This is completely useless and only done for `Put'.
buf.writeInt(0); // We'll monkey patch this later.
}
}
nkeys_per_family += rpc.numKeyValues();
nrpcs_per_key++;
nbytes_per_family += rpc.payloadSize();
rpc.serializePayload(buf);
prev = rpc;
} // Yay, we made it!
if (use_multi) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing junk for the last `Action'. See comment above.
buf.writeInt(nrpcs_per_key);
writeHBaseNull(buf); // Useless.
}
// Monkey-patch everything for the last set of edits.
buf.setInt(nkeys_per_family_index, nkeys_per_family);
if (prev.code() == PutRequest.CODE) {
buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
}
buf.setInt(nfamilies_index, nfamilies);
buf.setInt(nkeys_index, nkeys);
// Monkey-patch the number of regions affected by this RPC.
int header_length = 4 + 4 + 2 + method().length;
if (server_version >= RegionClient.SERVER_VERSION_092_OR_ABOVE) {
header_length += 1 + 8 + 4;
}
buf.setInt(header_length + 4 + 1 + 1, nregions);
return buf;
}
|
ChannelBuffer serialize(final byte server_version) {
// Due to the wire format expected by HBase, we need to group all the
// edits by region, then by key, then by family. HBase does this by
// building a crazy map-of-map-of-map-of-list-of-edits, but this is
// memory and time inefficient (lots of unnecessary references and
// O(n log n) operations). The approach we take here is to sort the
// list and iterate on it. Each time we find a different family or
// row key or region, we start a new set of edits. Because the RPC
// format needs to know the number of edits or bytes that follows in
// various places, we store a "0" value and then later monkey-patch it
// once we cross a row key / family / region boundary, because we can't
// efficiently tell ahead of time how many edits or bytes will follow
// until we cross such boundaries.
Collections.sort(batch, MULTI_CMP);
final ChannelBuffer buf = newBuffer(server_version,
predictSerializedSize(server_version));
buf.writeInt(1); // Number of parameters.
// Are we serializing a `multi' RPC, or `multiPut'?
final boolean use_multi = method() == MULTI;
{ // 1st and only param.
final int code = use_multi ? 66 : 57; // `MultiAction' or `MultiPut'.
buf.writeByte(code); // Type code for the parameter.
buf.writeByte(code); // Type code again (see HBASE-2877).
}
buf.writeInt(0); // How many regions do we want to affect?
// ^------ We'll monkey patch this at the end.
int nregions = 0;
int nkeys_index = -1;
int nkeys = 0;
int nfamilies_index = -1;
int nfamilies = 0;
int nkeys_per_family_index = -1;
int nkeys_per_family = 0;
int nbytes_per_family = 0;
int nrpcs_per_key = 0;
BatchableRpc prev = PutRequest.EMPTY_PUT;
for (final BatchableRpc rpc : batch) {
final byte[] region_name = rpc.getRegion().name();
final boolean new_region = !Bytes.equals(prev.getRegion().name(),
region_name);
final byte[] family = rpc.family();
final boolean new_key = (new_region
|| prev.code() != rpc.code()
|| !Bytes.equals(prev.key, rpc.key)
|| family == DeleteRequest.WHOLE_ROW);
final boolean new_family = new_key || !Bytes.equals(prev.family(),
family);
if (new_key && use_multi && nkeys_index > 0) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing useless junk from `Action'. After serializing its
// `action' (which implements an interface awesomely named `Row'),
// HBase adds the index of the `action' as the server will sort
// actions by key. This is pretty useless as if the client was
// sorting things before sending them off to the server, like we
// do, then we wouldn't need to pass an index to be able to match
// up requests and responses. Since we don't need this index, we
// instead use this field for another purpose: remembering how
// many RPCs we sent for this particular key. This will help us
// when de-serializing the response.
buf.writeInt(nrpcs_per_key);
nrpcs_per_key = 0;
// Then, because an `Action' can also contain a result, the code
// also serializes that. Of course for us end-users, this is stupid
// because we never send a result along with our request.
writeHBaseNull(buf);
}
if (new_region) {
// Monkey-patch the number of edits of the previous region.
if (nkeys_index > 0) {
buf.setInt(nkeys_index, nkeys);
nkeys = 0;
}
nregions++;
writeByteArray(buf, region_name); // The region name.
nkeys_index = buf.writerIndex();
// Number of keys for which we have RPCs for this region.
buf.writeInt(0); // We'll monkey patch this later.
}
final byte[] key = rpc.key;
if (new_key) {
// Monkey-patch the number of families of the previous key.
if (nfamilies_index > 0) {
buf.setInt(nfamilies_index, nfamilies);
nfamilies = 0;
}
if (use_multi) {
// Serialize an `Action' for the RPCs on this row.
buf.writeByte(65); // Code for an `Action' object.
buf.writeByte(65); // Code again (see HBASE-2877).
// Inside the action, serialize a `Put' object.
buf.writeByte(64); // Code for a `Row' object.
buf.writeByte(rpc.code()); // Code this object.
}
nkeys++;
// Right now we only support batching puts. In the future this part
// of the code will have to change to also want to allow get/deletes.
// The follow serializes a `Put'.
buf.writeByte(rpc.version(server_version)); // Undocumented versioning.
writeByteArray(buf, key); // The row key.
// This timestamp is unused, only the KeyValue-level timestamp is
// used, except in one case: whole-row deletes. In that case only,
// this timestamp is used by the RegionServer to create per-family
// deletes for that row. See HRegion.prepareDelete() for more info.
buf.writeLong(rpc.timestamp); // Timestamp.
buf.writeLong(RowLock.NO_LOCK); // Lock ID.
buf.writeByte(rpc.durable ? 0x01 : 0x00); // Use the WAL?
nfamilies_index = buf.writerIndex();
// Number of families that follow.
buf.writeInt(0); // We'll monkey patch this later.
}
if (new_family) {
// Monkey-patch the number and size of edits for the previous family.
if (nkeys_per_family_index > 0) {
buf.setInt(nkeys_per_family_index, nkeys_per_family);
if (prev.code() == PutRequest.CODE) {
buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
}
nkeys_per_family = 0;
nbytes_per_family = 0;
}
if (family == DeleteRequest.WHOLE_ROW) {
prev = rpc; // Short circuit. We have no KeyValue to write.
continue; // So loop again directly.
}
nfamilies++;
writeByteArray(buf, family); // The column family.
nkeys_per_family_index = buf.writerIndex();
// Number of "KeyValues" that follow.
buf.writeInt(0); // We'll monkey patch this later.
if (rpc.code() == PutRequest.CODE) {
// Total number of bytes taken by those "KeyValues".
// This is completely useless and only done for `Put'.
buf.writeInt(0); // We'll monkey patch this later.
}
}
nkeys_per_family += rpc.numKeyValues();
nrpcs_per_key++;
nbytes_per_family += rpc.payloadSize();
rpc.serializePayload(buf);
prev = rpc;
} // Yay, we made it!
if (use_multi) {
buf.writeInt(0); // Number of "attributes" for the last key (none).
// Trailing junk for the last `Action'. See comment above.
buf.writeInt(nrpcs_per_key);
writeHBaseNull(buf); // Useless.
}
// Note: the only case where nkeys_per_family_index remained -1 throughout
// this whole ordeal is where we didn't have any KV to serialize because
// every RPC was a `DeleteRequest.WHOLE_ROW'.
if (nkeys_per_family_index > 0) {
// Monkey-patch everything for the last set of edits.
buf.setInt(nkeys_per_family_index, nkeys_per_family);
if (prev.code() == PutRequest.CODE) {
buf.setInt(nkeys_per_family_index + 4, nbytes_per_family);
}
}
buf.setInt(nfamilies_index, nfamilies);
buf.setInt(nkeys_index, nkeys);
// Monkey-patch the number of regions affected by this RPC.
int header_length = 4 + 4 + 2 + method().length;
if (server_version >= RegionClient.SERVER_VERSION_092_OR_ABOVE) {
header_length += 1 + 8 + 4;
}
buf.setInt(header_length + 4 + 1 + 1, nregions);
return buf;
}
|
diff --git a/test/src/org/bouncycastle/crypto/test/ElGamalTest.java b/test/src/org/bouncycastle/crypto/test/ElGamalTest.java
index 7af5121e..3bcbc9df 100644
--- a/test/src/org/bouncycastle/crypto/test/ElGamalTest.java
+++ b/test/src/org/bouncycastle/crypto/test/ElGamalTest.java
@@ -1,203 +1,203 @@
package org.bouncycastle.crypto.test;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.engines.ElGamalEngine;
import org.bouncycastle.crypto.generators.ElGamalKeyPairGenerator;
import org.bouncycastle.crypto.generators.ElGamalParametersGenerator;
import org.bouncycastle.crypto.params.ElGamalKeyGenerationParameters;
import org.bouncycastle.crypto.params.ElGamalParameters;
import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters;
import org.bouncycastle.crypto.params.ElGamalPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.util.test.SimpleTest;
import java.math.BigInteger;
import java.security.SecureRandom;
public class ElGamalTest
extends SimpleTest
{
private BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
private BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
private BigInteger g768 = new BigInteger("7c240073c1316c621df461b71ebb0cdcc90a6e5527e5e126633d131f87461c4dc4afc60c2cb0f053b6758871489a69613e2a8b4c8acde23954c08c81cbd36132cfd64d69e4ed9f8e51ed6e516297206672d5c0a69135df0a5dcf010d289a9ca1", 16);
private BigInteger p768 = new BigInteger("8c9dd223debed1b80103b8b309715be009d48860ed5ae9b9d5d8159508efd802e3ad4501a7f7e1cfec78844489148cd72da24b21eddd01aa624291c48393e277cfc529e37075eccef957f3616f962d15b44aeab4039d01b817fde9eaa12fd73f", 16);
private BigInteger g1024 = new BigInteger("1db17639cdf96bc4eabba19454f0b7e5bd4e14862889a725c96eb61048dcd676ceb303d586e30f060dbafd8a571a39c4d823982117da5cc4e0f89c77388b7a08896362429b94a18a327604eb7ff227bffbc83459ade299e57b5f77b50fb045250934938efa145511166e3197373e1b5b1e52de713eb49792bedde722c6717abf", 16);
private BigInteger p1024 = new BigInteger("a00e283b3c624e5b2b4d9fbc2653b5185d99499b00fd1bf244c6f0bb817b4d1c451b2958d62a0f8a38caef059fb5ecd25d75ed9af403f5b5bdab97a642902f824e3c13789fed95fa106ddfe0ff4a707c85e2eb77d49e68f2808bcea18ce128b178cd287c6bc00efa9a1ad2a673fe0dceace53166f75b81d6709d5f8af7c66bb7", 16);
public String getName()
{
return "ElGamal";
}
private void testEnc(
int size,
int privateValueSize,
BigInteger g,
BigInteger p)
{
ElGamalParameters dhParams = new ElGamalParameters(p, g, privateValueSize);
ElGamalKeyGenerationParameters params = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams);
ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator();
kpGen.init(params);
//
// generate pair
//
AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters)pair.getPrivate();
checkKeySize(privateValueSize, pv);
ElGamalEngine e = new ElGamalEngine();
e.init(true, pu);
if (e.getOutputBlockSize() != size / 4)
{
fail(size + " getOutputBlockSize() on encryption failed.");
}
String message = "This is a test";
byte[] pText = message.getBytes();
byte[] cText = e.processBlock(pText, 0, pText.length);
e.init(false, pv);
if (e.getOutputBlockSize() != (size / 8) - 1)
{
fail(size + " getOutputBlockSize() on decryption failed.");
}
pText = e.processBlock(cText, 0, cText.length);
if (!message.equals(new String(pText)))
{
fail(size + " bit test failed");
}
e.init(true, pu);
byte[] bytes = new byte[e.getInputBlockSize() + 2];
try
{
e.processBlock(bytes, 0, bytes.length);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
bytes[0] = (byte)0xff;
e.processBlock(bytes, 0, bytes.length - 1);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
- bytes[0] = (byte)0x3f;
+ bytes[0] = (byte)0x7f;
e.processBlock(bytes, 0, bytes.length - 1);
}
catch (DataLengthException ex)
{
fail("in range block failed");
}
}
private void checkKeySize(
int privateValueSize,
ElGamalPrivateKeyParameters priv)
{
if (privateValueSize != 0)
{
if (priv.getX().bitLength() != privateValueSize)
{
fail("limited key check failed for key size " + privateValueSize);
}
}
}
/**
* this test is can take quiet a while
*/
private void testGeneration(
int size)
{
ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();
pGen.init(size, 10, new SecureRandom());
ElGamalParameters elParams = pGen.generateParameters();
ElGamalKeyGenerationParameters params = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator();
kpGen.init(params);
//
// generate first pair
//
AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters)pair.getPrivate();
ElGamalEngine e = new ElGamalEngine();
e.init(true, new ParametersWithRandom(pu, new SecureRandom()));
String message = "This is a test";
byte[] pText = message.getBytes();
byte[] cText = e.processBlock(pText, 0, pText.length);
e.init(false, pv);
pText = e.processBlock(cText, 0, cText.length);
if (!message.equals(new String(pText)))
{
fail("generation test failed");
}
}
public void performTest()
{
testEnc(512, 0, g512, p512);
testEnc(768, 0, g768, p768);
testEnc(1024, 0, g1024, p1024);
testEnc(512, 64, g512, p512);
testEnc(768, 128, g768, p768);
//
// generation test.
//
testGeneration(258);
}
public static void main(
String[] args)
{
runTest(new ElGamalTest());
}
}
| true | true |
private void testEnc(
int size,
int privateValueSize,
BigInteger g,
BigInteger p)
{
ElGamalParameters dhParams = new ElGamalParameters(p, g, privateValueSize);
ElGamalKeyGenerationParameters params = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams);
ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator();
kpGen.init(params);
//
// generate pair
//
AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters)pair.getPrivate();
checkKeySize(privateValueSize, pv);
ElGamalEngine e = new ElGamalEngine();
e.init(true, pu);
if (e.getOutputBlockSize() != size / 4)
{
fail(size + " getOutputBlockSize() on encryption failed.");
}
String message = "This is a test";
byte[] pText = message.getBytes();
byte[] cText = e.processBlock(pText, 0, pText.length);
e.init(false, pv);
if (e.getOutputBlockSize() != (size / 8) - 1)
{
fail(size + " getOutputBlockSize() on decryption failed.");
}
pText = e.processBlock(cText, 0, cText.length);
if (!message.equals(new String(pText)))
{
fail(size + " bit test failed");
}
e.init(true, pu);
byte[] bytes = new byte[e.getInputBlockSize() + 2];
try
{
e.processBlock(bytes, 0, bytes.length);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
bytes[0] = (byte)0xff;
e.processBlock(bytes, 0, bytes.length - 1);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
bytes[0] = (byte)0x3f;
e.processBlock(bytes, 0, bytes.length - 1);
}
catch (DataLengthException ex)
{
fail("in range block failed");
}
}
|
private void testEnc(
int size,
int privateValueSize,
BigInteger g,
BigInteger p)
{
ElGamalParameters dhParams = new ElGamalParameters(p, g, privateValueSize);
ElGamalKeyGenerationParameters params = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams);
ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator();
kpGen.init(params);
//
// generate pair
//
AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters)pair.getPrivate();
checkKeySize(privateValueSize, pv);
ElGamalEngine e = new ElGamalEngine();
e.init(true, pu);
if (e.getOutputBlockSize() != size / 4)
{
fail(size + " getOutputBlockSize() on encryption failed.");
}
String message = "This is a test";
byte[] pText = message.getBytes();
byte[] cText = e.processBlock(pText, 0, pText.length);
e.init(false, pv);
if (e.getOutputBlockSize() != (size / 8) - 1)
{
fail(size + " getOutputBlockSize() on decryption failed.");
}
pText = e.processBlock(cText, 0, cText.length);
if (!message.equals(new String(pText)))
{
fail(size + " bit test failed");
}
e.init(true, pu);
byte[] bytes = new byte[e.getInputBlockSize() + 2];
try
{
e.processBlock(bytes, 0, bytes.length);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
bytes[0] = (byte)0xff;
e.processBlock(bytes, 0, bytes.length - 1);
fail("out of range block not detected");
}
catch (DataLengthException ex)
{
// expected
}
try
{
bytes[0] = (byte)0x7f;
e.processBlock(bytes, 0, bytes.length - 1);
}
catch (DataLengthException ex)
{
fail("in range block failed");
}
}
|
diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java
index 8513a12..190e494 100644
--- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java
+++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java
@@ -1,372 +1,376 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
/**
* Multiverse's {@link Listener} for players.
*/
public class MVPlayerListener implements Listener {
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private final PermissionTools pt;
private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>();
public MVPlayerListener(MultiverseCore plugin) {
this.plugin = plugin;
worldManager = plugin.getMVWorldManager();
pt = new PermissionTools(plugin);
}
/**
* @return the playerWorld-map
*/
public Map<String, String> getPlayerWorld() {
return playerWorld;
}
/**
* This method is called when a player respawns.
* @param event The Event that was fired.
*/
@EventHandler(priority = EventPriority.LOW)
public void playerRespawn(PlayerRespawnEvent event) {
World world = event.getPlayer().getWorld();
MultiverseWorld mvWorld = this.worldManager.getMVWorld(world.getName());
// If it's not a World MV manages we stop.
if (mvWorld == null) {
return;
}
if (mvWorld.getBedRespawn() && event.isBedSpawn()) {
this.plugin.log(Level.FINE, "Spawning " + event.getPlayer().getName() + " at their bed");
return;
}
// Get the instance of the World the player should respawn at.
MultiverseWorld respawnWorld = null;
if (this.worldManager.isMVWorld(mvWorld.getRespawnToWorld())) {
respawnWorld = this.worldManager.getMVWorld(mvWorld.getRespawnToWorld());
}
// If it's null then it either means the World doesn't exist or the value is blank, so we don't handle it.
// NOW: We'll always handle it to get more accurate spawns
if (respawnWorld != null) {
world = respawnWorld.getCBWorld();
}
// World has been set to the appropriate world
Location respawnLocation = getMostAccurateRespawnLocation(world);
MVRespawnEvent respawnEvent = new MVRespawnEvent(respawnLocation, event.getPlayer(), "compatability");
this.plugin.getServer().getPluginManager().callEvent(respawnEvent);
event.setRespawnLocation(respawnEvent.getPlayersRespawnLocation());
}
private Location getMostAccurateRespawnLocation(World w) {
MultiverseWorld mvw = this.worldManager.getMVWorld(w.getName());
if (mvw != null) {
return mvw.getSpawnLocation();
}
return w.getSpawnLocation();
}
/**
* This method is called when a player joins the server.
* @param event The Event that was fired.
*/
@EventHandler
public void playerJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
if (!p.hasPlayedBefore()) {
this.plugin.log(Level.FINER, "Player joined for the FIRST time!");
if (plugin.getMVConfig().getFirstSpawnOverride()) {
this.plugin.log(Level.FINE, "Moving NEW player to(firstspawnoverride): "
+ worldManager.getFirstSpawnWorld().getSpawnLocation());
this.sendPlayerToDefaultWorld(p);
}
return;
} else {
this.plugin.log(Level.FINER, "Player joined AGAIN!");
if (this.plugin.getMVConfig().getEnforceAccess() // check this only if we're enforcing access!
&& !this.plugin.getMVPerms().hasPermission(p, "multiverse.access." + p.getWorld().getName(), false)) {
p.sendMessage("[MV] - Sorry you can't be in this world anymore!");
this.sendPlayerToDefaultWorld(p);
}
}
// Handle the Players GameMode setting for the new world.
this.handleGameModeAndFlight(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(p.getName(), p.getWorld().getName());
}
/**
* This method is called when a player changes worlds.
* @param event The Event that was fired.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void playerChangedWorld(PlayerChangedWorldEvent event) {
// Permissions now determine whether or not to handle a gamemode.
this.handleGameModeAndFlight(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(event.getPlayer().getName(), event.getPlayer().getWorld().getName());
}
/**
* This method is called when a player quits the game.
* @param event The Event that was fired.
*/
@EventHandler
public void playerQuit(PlayerQuitEvent event) {
this.plugin.removePlayerSession(event.getPlayer());
}
/**
* This method is called when a player teleports anywhere.
* @param event The Event that was fired.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void playerTeleport(PlayerTeleportEvent event) {
this.plugin.log(Level.FINER, "Got teleport event for player '"
+ event.getPlayer().getName() + "' with cause '" + event.getCause() + "'");
if (event.isCancelled()) {
return;
}
Player teleportee = event.getPlayer();
CommandSender teleporter = null;
String teleporterName = MultiverseCore.getPlayerTeleporter(teleportee.getName());
if (teleporterName != null) {
if (teleporterName.equals("CONSOLE")) {
this.plugin.log(Level.FINER, "We know the teleporter is the console! Magical!");
teleporter = this.plugin.getServer().getConsoleSender();
} else {
teleporter = this.plugin.getServer().getPlayer(teleporterName);
}
}
this.plugin.log(Level.FINER, "Inferred sender '" + teleporter + "' from name '"
+ teleporterName + "', fetched from name '" + teleportee.getName() + "'");
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
- if (fromWorld == null || toWorld == null)
+ if (toWorld == null) {
+ this.plugin.log(Level.FINE, "Player '" + teleportee.getName() + "' is teleporting to world '"
+ + event.getTo().getWorld().getName() + "' which is not managed by Multiverse-Core. No further "
+ + "actions will be taken by Multiverse-Core.");
return;
+ }
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Teleporting to the same world.
this.plugin.log(Level.FINER, "Player '" + teleportee.getName() + "' is teleporting to the same world.");
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
// TODO: Refactor these lines.
// Charge the teleporter
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, teleporter, teleportee, true));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have the FUNDS required to enter it.");
return;
}
// Check if player is allowed to enter the world if we're enforcing permissions
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
return;
}
} else {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
}
// Does a limit actually exist?
if (toWorld.getPlayerLimit() > -1) {
// Are there equal or more people on the world than the limit?
if (toWorld.getCBWorld().getPlayers().size() >= toWorld.getPlayerLimit()) {
// Ouch the world is full, lets see if the player can bypass that limitation
if (!pt.playerCanBypassPlayerLimit(toWorld, teleporter, teleportee)) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
event.setCancelled(true);
return;
}
}
}
// By this point anything cancelling the event has returned on the method, meaning the teleport is a success \o/
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
private void stateSuccess(String playerName, String worldName) {
this.plugin.log(Level.FINE, "MV-Core is allowing Player '" + playerName
+ "' to go to '" + worldName + "'.");
}
/**
* This method is called to adjust the portal location to the actual portal location (and not
* right outside of it.
* @param event The Event that was fired.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void playerPortalCheck(PlayerPortalEvent event) {
if (event.isCancelled() || event.getFrom() == null) {
return;
}
// REMEMBER! getTo MAY be NULL HERE!!!
// If the player was actually outside of the portal, adjust the from location
if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.PORTAL) {
Location newloc = this.plugin.getSafeTTeleporter().findPortalBlockNextTo(event.getFrom());
// TODO: Fix this. Currently, we only check for PORTAL blocks. I'll have to figure out what
// TODO: we want to do here.
if (newloc != null) {
event.setFrom(newloc);
}
}
// Wait for the adjust, then return!
if (event.getTo() == null) {
return;
}
}
/**
* This method is called when a player actually portals via a vanilla style portal.
* @param event The Event that was fired.
*/
@EventHandler(priority = EventPriority.HIGH)
public void playerPortal(PlayerPortalEvent event) {
if (event.isCancelled() || (event.getFrom() == null)) {
return;
}
// The adjust should have happened much earlier.
if (event.getTo() == null) {
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world.");
return;
}
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, event.getPlayer(), event.getPlayer(), true));
if (event.isCancelled()) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have the FUNDS required to enter.");
return;
}
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, event.getPlayer(), event.getPlayer()));
if (event.isCancelled()) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have: multiverse.access." + event.getTo().getWorld().getName());
}
} else {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was allowed to go to '" + event.getTo().getWorld().getName()
+ "' because enforceaccess is off.");
}
if (!plugin.getMVConfig().isUsingDefaultPortalSearch() && event.getPortalTravelAgent() != null) {
event.getPortalTravelAgent().setSearchRadius(plugin.getMVConfig().getPortalSearchRadius());
}
}
private void sendPlayerToDefaultWorld(final Player player) {
// Remove the player 1 tick after the login. I'm sure there's GOT to be a better way to do this...
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
player.teleport(plugin.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation());
}
}, 1L);
}
// FOLLOWING 2 Methods and Private class handle Per Player GameModes.
private void handleGameModeAndFlight(Player player, World world) {
MultiverseWorld mvWorld = this.worldManager.getMVWorld(world.getName());
if (mvWorld != null) {
this.handleGameModeAndFlight(player, mvWorld);
} else {
this.plugin.log(Level.FINER, "Not handling gamemode and flight for world '" + world.getName()
+ "' not managed by Multiverse.");
}
}
/**
* Handles the gamemode for the specified {@link Player}.
* @param player The {@link Player}.
* @param world The world the player is in.
*/
public void handleGameModeAndFlight(final Player player, final MultiverseWorld world) {
// We perform this task one tick later to MAKE SURE that the player actually reaches the
// destination world, otherwise we'd be changing the player mode if they havent moved anywhere.
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
if (!MVPlayerListener.this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
Logging.fine("Handling gamemode for player: %s, Changing to %s", player.getName(), world.getGameMode().toString());
Logging.finest("From World: %s", player.getWorld());
Logging.finest("To World: %s", world);
player.setGameMode(world.getGameMode());
// Check if their flight mode should change
// TODO need a override permission for this
if (player.getAllowFlight() && !world.getAllowFlight() && player.getGameMode() != GameMode.CREATIVE) {
player.setAllowFlight(false);
if (player.isFlying()) {
player.setFlying(false);
}
} else if (world.getAllowFlight()) {
if (player.getGameMode() == GameMode.CREATIVE) {
player.setAllowFlight(true);
}
}
} else {
Logging.fine("The gamemode/allowfly was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName());
}
} else {
MVPlayerListener.this.plugin.log(Level.FINE, "Player: " + player.getName() + " is IMMUNE to gamemode changes!");
}
}
}, 1L);
}
}
| false | true |
public void playerTeleport(PlayerTeleportEvent event) {
this.plugin.log(Level.FINER, "Got teleport event for player '"
+ event.getPlayer().getName() + "' with cause '" + event.getCause() + "'");
if (event.isCancelled()) {
return;
}
Player teleportee = event.getPlayer();
CommandSender teleporter = null;
String teleporterName = MultiverseCore.getPlayerTeleporter(teleportee.getName());
if (teleporterName != null) {
if (teleporterName.equals("CONSOLE")) {
this.plugin.log(Level.FINER, "We know the teleporter is the console! Magical!");
teleporter = this.plugin.getServer().getConsoleSender();
} else {
teleporter = this.plugin.getServer().getPlayer(teleporterName);
}
}
this.plugin.log(Level.FINER, "Inferred sender '" + teleporter + "' from name '"
+ teleporterName + "', fetched from name '" + teleportee.getName() + "'");
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (fromWorld == null || toWorld == null)
return;
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Teleporting to the same world.
this.plugin.log(Level.FINER, "Player '" + teleportee.getName() + "' is teleporting to the same world.");
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
// TODO: Refactor these lines.
// Charge the teleporter
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, teleporter, teleportee, true));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have the FUNDS required to enter it.");
return;
}
// Check if player is allowed to enter the world if we're enforcing permissions
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
return;
}
} else {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
}
// Does a limit actually exist?
if (toWorld.getPlayerLimit() > -1) {
// Are there equal or more people on the world than the limit?
if (toWorld.getCBWorld().getPlayers().size() >= toWorld.getPlayerLimit()) {
// Ouch the world is full, lets see if the player can bypass that limitation
if (!pt.playerCanBypassPlayerLimit(toWorld, teleporter, teleportee)) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
event.setCancelled(true);
return;
}
}
}
// By this point anything cancelling the event has returned on the method, meaning the teleport is a success \o/
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
|
public void playerTeleport(PlayerTeleportEvent event) {
this.plugin.log(Level.FINER, "Got teleport event for player '"
+ event.getPlayer().getName() + "' with cause '" + event.getCause() + "'");
if (event.isCancelled()) {
return;
}
Player teleportee = event.getPlayer();
CommandSender teleporter = null;
String teleporterName = MultiverseCore.getPlayerTeleporter(teleportee.getName());
if (teleporterName != null) {
if (teleporterName.equals("CONSOLE")) {
this.plugin.log(Level.FINER, "We know the teleporter is the console! Magical!");
teleporter = this.plugin.getServer().getConsoleSender();
} else {
teleporter = this.plugin.getServer().getPlayer(teleporterName);
}
}
this.plugin.log(Level.FINER, "Inferred sender '" + teleporter + "' from name '"
+ teleporterName + "', fetched from name '" + teleportee.getName() + "'");
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (toWorld == null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName() + "' is teleporting to world '"
+ event.getTo().getWorld().getName() + "' which is not managed by Multiverse-Core. No further "
+ "actions will be taken by Multiverse-Core.");
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Teleporting to the same world.
this.plugin.log(Level.FINER, "Player '" + teleportee.getName() + "' is teleporting to the same world.");
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
// TODO: Refactor these lines.
// Charge the teleporter
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, teleporter, teleportee, true));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have the FUNDS required to enter it.");
return;
}
// Check if player is allowed to enter the world if we're enforcing permissions
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
return;
}
} else {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
}
// Does a limit actually exist?
if (toWorld.getPlayerLimit() > -1) {
// Are there equal or more people on the world than the limit?
if (toWorld.getCBWorld().getPlayers().size() >= toWorld.getPlayerLimit()) {
// Ouch the world is full, lets see if the player can bypass that limitation
if (!pt.playerCanBypassPlayerLimit(toWorld, teleporter, teleportee)) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
event.setCancelled(true);
return;
}
}
}
// By this point anything cancelling the event has returned on the method, meaning the teleport is a success \o/
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
|
diff --git a/src/main/java/org/apache/maven/plugin/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugin/deploy/DeployMojo.java
index 3a26558..fe40b11 100644
--- a/src/main/java/org/apache/maven/plugin/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugin/deploy/DeployMojo.java
@@ -1,543 +1,546 @@
package org.apache.maven.plugin.deploy;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.lifecycle.internal.LifecycleDependencyResolver;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.*;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
/**
* Deploys an artifact to remote repository.
*
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @author <a href="mailto:[email protected]">John Casey (refactoring only)</a>
* @version $Id: DeployMojo.java 1160164 2011-08-22 09:38:32Z stephenc $
* @goal deploy
* @phase deploy
* @threadSafe
* @requiresDependencyResolution
*/
public class DeployMojo extends AbstractDeployMojo {
private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile( "(.+)::(.+)::(.+)" );
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* @parameter default-value="${session}"
* @required
* @readonly
*/
protected MavenSession session;
/**
* @parameter default-value="${project.packaging}"
* @required
* @readonly
*/
private String packaging;
/**
* @parameter default-value="${project.file}"
* @required
* @readonly
*/
private File pomFile;
/**
* @parameter default-value=false expression="${deployDependencies}"
* @required
*/
protected boolean deployDependencies;
/**
* @parameter default-value=false expression="${filterPom}"
* @required
*/
private boolean filterPom;
/**
* @parameter default-value=false expression="${failureIsAnOption}"
* @required
*/
private boolean failureIsAnOption;
/**
* Specifies an alternative repository to which the project artifacts should be deployed ( other
* than those specified in <distributionManagement> ).
* <br/>
* Format: id::layout::url
*
* @parameter expression="${altDeploymentRepository}"
*/
private String altDeploymentRepository;
/**
* @parameter default-value="${project.attachedArtifacts}
* @required
* @readonly
*/
private List attachedArtifacts;
/**
* Set this to 'true' to bypass artifact deploy
*
* @parameter expression="${maven.deploy.skip}" default-value="false"
* @since 2.4
*/
private boolean skip;
/**
* Used to look up Artifacts in the remote repository.
*
* @parameter expression=
* "${component.org.apache.maven.lifecycle.internal.LifecycleDependencyResolver}"
* @required
* @readonly
*/
protected LifecycleDependencyResolver lcdResolver;
/**
* List of Remote Repositories used by the resolver
*
* @parameter expression="${project.remoteArtifactRepositories}"
* @readonly
* @required
*/
protected java.util.List remoteRepos;
/**
* Location of the local repository.
*
* @parameter expression="${localRepository}"
* @readonly
* @required
*/
protected org.apache.maven.artifact.repository.ArtifactRepository local;
/**
* artifact handling.
*
* @parameter expression="${component.org.apache.maven.artifact.handler.manager.ArtifactHandlerManager}"
* @readonly
* @required
*/
protected ArtifactHandlerManager handlerManager;
/**
* Used to create a model
*
* @parameter expression=
* "${component.org.apache.maven.project.ProjectBuilder}"
* @required
* @readonly
*/
protected ProjectBuilder mavenProjectBuilder;
/**
* @parameter
*/
private List<String> blackListPatterns;
private List<Pattern> theBlackListPatterns = new LinkedList<Pattern>();
private Map<String, Artifact> pomArtifacts = new HashMap<String, Artifact>();
/**
* @parameter
*/
private List<String> whiteListPatterns;
private List<Pattern> theWhiteListPatterns = new LinkedList<Pattern>();
public void execute()
throws MojoExecutionException, MojoFailureException {
Set<Artifact> toBeDeployedArtifacts = new HashSet<Artifact>();
toBeDeployedArtifacts.add( project.getArtifact() );
getLog().debug( "Deploying project: " + project.getArtifactId() );
try {
executeWithArtifacts( toBeDeployedArtifacts );
}
catch (Exception e) {
throw new MojoExecutionException( "Error while resolving artifacts", e );
}
}
public void executeWithArtifacts(Set<Artifact> toBeDeployedArtifacts)
throws MojoExecutionException, MojoFailureException, LifecycleExecutionException {
if (skip) {
getLog().info( "Skipping artifact deployment" );
return;
}
failIfOffline();
populatePatterns();
ArtifactRepository repo = getDeploymentRepository();
String protocol = repo.getProtocol();
if (protocol.equalsIgnoreCase( "scp" )) {
File sshFile = new File( System.getProperty( "user.home" ), ".ssh" );
if (!sshFile.exists()) {
sshFile.mkdirs();
}
}
// create a selection of artifacts that need to be deployed
if (deployDependencies) {
toBeDeployedArtifacts.clear();
toBeDeployedArtifacts.add( project.getArtifact() );
toBeDeployedArtifacts.addAll( project.getArtifacts() );
}
int swallowed = 0;
for (Object iter : toBeDeployedArtifacts) {
try {
Artifact artifactTBD = (Artifact) iter;
if (!isAuthorized( artifactTBD )) {
getLog().debug( "Skipping artifact: " + artifactTBD.getId() );
continue;
}
getLog().debug( "Deploying artifact: " + artifactTBD.getId() );
- if (artifactTBD.getFile() == null) {
+ if (artifactTBD.getFile() == null && !artifactTBD.getType().equals( "pom" )) {
getLog().debug( "Skipping deployment of " + artifactTBD.getId() );
continue;
+ } else if (artifactTBD.getFile() == null) {
+ // pom artifact
+ artifactTBD.setFile( pomFile );
}
Artifact thePomArtifact;
if (artifactTBD.getType().equals( "pom" )) {
thePomArtifact = artifactTBD;
} else {
String mapKey = String.format( "%s:%s:%s", artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion() );
if (pomArtifacts.containsKey( mapKey )) {
thePomArtifact = pomArtifacts.get( mapKey );
} else {
thePomArtifact = new DefaultArtifact( artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion(), "", "pom", "", new PomArtifactHandler() );
// we resolve the pom file first
HashSet<Artifact> deps = new HashSet<Artifact>();
deps.addAll( project.getDependencyArtifacts() );
deps.add( thePomArtifact );
project.setDependencyArtifacts( deps );
Set<String> scopes = Collections.singleton( Artifact.SCOPE_RUNTIME );
lcdResolver.resolveProjectDependencies( project, scopes, scopes, session, false, Collections.<Artifact>emptySet() );
pomArtifacts.put( mapKey, thePomArtifact );
}
}
if (filterPom) {
filterPom( thePomArtifact );
}
pomFile = thePomArtifact.getFile();
boolean isPomArtifact = "pom".equals( artifactTBD.getType() );
try {
if (isPomArtifact) {
deploy( pomFile, artifactTBD, repo, getLocalRepository() );
} else {
File file = artifactTBD.getFile();
if (file != null && file.isFile()) {
deploy( file, artifactTBD, repo, getLocalRepository() );
} else if (!attachedArtifacts.isEmpty()) {
getLog().info( "No primary artifact to deploy, deploying attached artifacts instead." );
if (updateReleaseInfo) {
thePomArtifact.setRelease( true );
}
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
// propagate the timestamped version to the main artifact for the attached artifacts
// to pick it up
artifactTBD.setResolvedVersion( thePomArtifact.getVersion() );
} else {
String message = "The packaging for this project did not " + "assign a file to the build artifact";
System.err.println( "The artifact on which we crash: " + artifactTBD.getId() );
throw new MojoExecutionException( message );
}
}
if (filterPom) {
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
}
}
catch (ArtifactDeploymentException e) {
throw new MojoExecutionException( "Failed to deploy artifact", e );
}
}
catch (MojoExecutionException e) {
if (!failureIsAnOption)
throw e;
swallowed++;
getLog().warn( "failed to deploy " + ((Artifact) iter).getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
for (Iterator i = attachedArtifacts.iterator(); i.hasNext(); ) {
Artifact attached = (Artifact) i.next();
try {
deploy( attached.getFile(), attached, repo, getLocalRepository() );
}
catch (ArtifactDeploymentException e) {
if (!failureIsAnOption)
throw new MojoExecutionException( "Failed to deploy artifact", e );
swallowed++;
getLog().warn( "failed to deploy " + attached.getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
if (swallowed > 0) {
getLog().warn( "I swallowed " + swallowed + " deployment exceptions. If you want me to fail on this please" +
" unset failureIsAnOption" );
}
}
private ArtifactRepository getDeploymentRepository()
throws MojoExecutionException, MojoFailureException {
ArtifactRepository repo = null;
if (altDeploymentRepository != null) {
getLog().info( "Using alternate deployment repository " + altDeploymentRepository );
Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher( altDeploymentRepository );
if (!matcher.matches()) {
throw new MojoFailureException( altDeploymentRepository, "Invalid syntax for repository.",
"Invalid syntax for alternative repository. Use \"id::layout::url\"." );
} else {
String id = matcher.group( 1 ).trim();
String layout = matcher.group( 2 ).trim();
String url = matcher.group( 3 ).trim();
ArtifactRepositoryLayout repoLayout = getLayout( layout );
repo = repositoryFactory.createDeploymentArtifactRepository( id, url, repoLayout, true );
}
}
if (repo == null) {
repo = project.getDistributionManagementArtifactRepository();
}
if (repo == null) {
String msg = "Deployment failed: repository element was not specified in the POM inside"
+ " distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter";
throw new MojoExecutionException( msg );
}
return repo;
}
private void filterPom(Artifact thePomArtifact)
throws MojoExecutionException {
getLog().debug( "Filtering pom file: " + thePomArtifact.getId() );
if (!thePomArtifact.getType().equals( "pom" )) {
getLog().debug( "Ignoring filtering of a non-pom file" );
throw new MojoExecutionException( "Don't ask me to filter a non pom file" );
}
try {
// Try to remove the broken distributionmanagement element from downloaded poms
// otherwise maven might refuse to parse those poms to projects
Model brokenModel = (new DefaultModelReader()).read( thePomArtifact.getFile(), null );
brokenModel.setDistributionManagement( null );
// set aside the packaging. We will restore it later to prevent maven from choking on
// exotic packaging types
String theRealPackaging = brokenModel.getPackaging();
brokenModel.setPackaging( null );
// also remove the module section so we don't fail on aggregator projects
brokenModel.setModules( null );
ModelWriter modelWriter = new DefaultModelWriter();
getLog().debug( "Overwriting pom file to remove distributionmanagement: " + thePomArtifact.getFile().getAbsolutePath() );
//we write the new pom file to a temp file as to not interfere with 'official' pom files in the repo
File tempFile = File.createTempFile( "deploy-plugin", "pom" );
modelWriter.write( tempFile, null, brokenModel );
thePomArtifact.setFile( tempFile );
// first build a project from the pom artifact
MavenProject bareProject = mavenProjectBuilder.build( thePomArtifact.getFile(), project.getProjectBuildingRequest() )
.getProject();
// get the model and start filtering useless stuff
Model currentModel = bareProject.getModel();
currentModel.setPackaging( theRealPackaging );
currentModel.setParent( null );
currentModel.setBuild( null );
currentModel.setCiManagement( null );
currentModel.setContributors( null );
currentModel.setCiManagement( null );
currentModel.setDevelopers( null );
currentModel.setIssueManagement( null );
currentModel.setMailingLists( null );
currentModel.setProfiles( null );
currentModel.setModules( null );
currentModel.setDistributionManagement( null );
currentModel.setPluginRepositories( null );
currentModel.setReporting( null );
currentModel.setReports( null );
currentModel.setRepositories( null );
currentModel.setScm( null );
currentModel.setUrl( null );
List<Dependency> goodDeps = new ArrayList<Dependency>();
for (Object obj : bareProject.getDependencies()) {
Dependency dep = (Dependency) obj;
String scope = dep.getScope();
if (null == scope || !scope.equals( Artifact.SCOPE_TEST )) {
goodDeps.add( dep );
}
}
currentModel.setDependencies( goodDeps );
currentModel.setDependencyManagement( null );
currentModel.setProperties( null );
// spit the merged model to the output file.
getLog().debug( "Overwriting pom file with filtered pom: " + thePomArtifact.getFile().getAbsolutePath() );
modelWriter.write( thePomArtifact.getFile(), null, currentModel );
}
catch (Exception e) {
throw new MojoExecutionException( e.getMessage(), e );
}
}
private void populatePatterns() {
if (blackListPatterns != null) {
for (String blackList : blackListPatterns) {
getLog().debug( "Adding black list pattern: " + blackList );
theBlackListPatterns.add( Pattern.compile( blackList ) );
}
}
if (whiteListPatterns != null) {
for (String whiteList : whiteListPatterns) {
getLog().debug( "Adding white list pattern: " + whiteList );
theWhiteListPatterns.add( Pattern.compile( whiteList ) );
}
}
}
private boolean isAuthorized(Artifact artifact) {
String target = artifact.getId();
for (Pattern black : theBlackListPatterns) {
if (black.matcher( target ).matches()) {
getLog().debug( target + " matches blacklist pattern " + black.toString() );
return false;
}
}
for (Pattern white : theWhiteListPatterns) {
if (!white.matcher( target ).matches()) {
getLog().debug( target + " not matches whitelist pattern " + white.toString() );
return false;
}
}
return true;
}
static class PomArtifactHandler implements ArtifactHandler {
public String getClassifier() {
return null;
}
public String getDirectory() {
return null;
}
public String getExtension() {
return "pom";
}
public String getLanguage() {
return "none";
}
public String getPackaging() {
return "pom";
}
public boolean isAddedToClasspath() {
return false;
}
public boolean isIncludesDependencies() {
return false;
}
}
}
| false | true |
public void executeWithArtifacts(Set<Artifact> toBeDeployedArtifacts)
throws MojoExecutionException, MojoFailureException, LifecycleExecutionException {
if (skip) {
getLog().info( "Skipping artifact deployment" );
return;
}
failIfOffline();
populatePatterns();
ArtifactRepository repo = getDeploymentRepository();
String protocol = repo.getProtocol();
if (protocol.equalsIgnoreCase( "scp" )) {
File sshFile = new File( System.getProperty( "user.home" ), ".ssh" );
if (!sshFile.exists()) {
sshFile.mkdirs();
}
}
// create a selection of artifacts that need to be deployed
if (deployDependencies) {
toBeDeployedArtifacts.clear();
toBeDeployedArtifacts.add( project.getArtifact() );
toBeDeployedArtifacts.addAll( project.getArtifacts() );
}
int swallowed = 0;
for (Object iter : toBeDeployedArtifacts) {
try {
Artifact artifactTBD = (Artifact) iter;
if (!isAuthorized( artifactTBD )) {
getLog().debug( "Skipping artifact: " + artifactTBD.getId() );
continue;
}
getLog().debug( "Deploying artifact: " + artifactTBD.getId() );
if (artifactTBD.getFile() == null) {
getLog().debug( "Skipping deployment of " + artifactTBD.getId() );
continue;
}
Artifact thePomArtifact;
if (artifactTBD.getType().equals( "pom" )) {
thePomArtifact = artifactTBD;
} else {
String mapKey = String.format( "%s:%s:%s", artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion() );
if (pomArtifacts.containsKey( mapKey )) {
thePomArtifact = pomArtifacts.get( mapKey );
} else {
thePomArtifact = new DefaultArtifact( artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion(), "", "pom", "", new PomArtifactHandler() );
// we resolve the pom file first
HashSet<Artifact> deps = new HashSet<Artifact>();
deps.addAll( project.getDependencyArtifacts() );
deps.add( thePomArtifact );
project.setDependencyArtifacts( deps );
Set<String> scopes = Collections.singleton( Artifact.SCOPE_RUNTIME );
lcdResolver.resolveProjectDependencies( project, scopes, scopes, session, false, Collections.<Artifact>emptySet() );
pomArtifacts.put( mapKey, thePomArtifact );
}
}
if (filterPom) {
filterPom( thePomArtifact );
}
pomFile = thePomArtifact.getFile();
boolean isPomArtifact = "pom".equals( artifactTBD.getType() );
try {
if (isPomArtifact) {
deploy( pomFile, artifactTBD, repo, getLocalRepository() );
} else {
File file = artifactTBD.getFile();
if (file != null && file.isFile()) {
deploy( file, artifactTBD, repo, getLocalRepository() );
} else if (!attachedArtifacts.isEmpty()) {
getLog().info( "No primary artifact to deploy, deploying attached artifacts instead." );
if (updateReleaseInfo) {
thePomArtifact.setRelease( true );
}
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
// propagate the timestamped version to the main artifact for the attached artifacts
// to pick it up
artifactTBD.setResolvedVersion( thePomArtifact.getVersion() );
} else {
String message = "The packaging for this project did not " + "assign a file to the build artifact";
System.err.println( "The artifact on which we crash: " + artifactTBD.getId() );
throw new MojoExecutionException( message );
}
}
if (filterPom) {
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
}
}
catch (ArtifactDeploymentException e) {
throw new MojoExecutionException( "Failed to deploy artifact", e );
}
}
catch (MojoExecutionException e) {
if (!failureIsAnOption)
throw e;
swallowed++;
getLog().warn( "failed to deploy " + ((Artifact) iter).getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
for (Iterator i = attachedArtifacts.iterator(); i.hasNext(); ) {
Artifact attached = (Artifact) i.next();
try {
deploy( attached.getFile(), attached, repo, getLocalRepository() );
}
catch (ArtifactDeploymentException e) {
if (!failureIsAnOption)
throw new MojoExecutionException( "Failed to deploy artifact", e );
swallowed++;
getLog().warn( "failed to deploy " + attached.getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
if (swallowed > 0) {
getLog().warn( "I swallowed " + swallowed + " deployment exceptions. If you want me to fail on this please" +
" unset failureIsAnOption" );
}
}
|
public void executeWithArtifacts(Set<Artifact> toBeDeployedArtifacts)
throws MojoExecutionException, MojoFailureException, LifecycleExecutionException {
if (skip) {
getLog().info( "Skipping artifact deployment" );
return;
}
failIfOffline();
populatePatterns();
ArtifactRepository repo = getDeploymentRepository();
String protocol = repo.getProtocol();
if (protocol.equalsIgnoreCase( "scp" )) {
File sshFile = new File( System.getProperty( "user.home" ), ".ssh" );
if (!sshFile.exists()) {
sshFile.mkdirs();
}
}
// create a selection of artifacts that need to be deployed
if (deployDependencies) {
toBeDeployedArtifacts.clear();
toBeDeployedArtifacts.add( project.getArtifact() );
toBeDeployedArtifacts.addAll( project.getArtifacts() );
}
int swallowed = 0;
for (Object iter : toBeDeployedArtifacts) {
try {
Artifact artifactTBD = (Artifact) iter;
if (!isAuthorized( artifactTBD )) {
getLog().debug( "Skipping artifact: " + artifactTBD.getId() );
continue;
}
getLog().debug( "Deploying artifact: " + artifactTBD.getId() );
if (artifactTBD.getFile() == null && !artifactTBD.getType().equals( "pom" )) {
getLog().debug( "Skipping deployment of " + artifactTBD.getId() );
continue;
} else if (artifactTBD.getFile() == null) {
// pom artifact
artifactTBD.setFile( pomFile );
}
Artifact thePomArtifact;
if (artifactTBD.getType().equals( "pom" )) {
thePomArtifact = artifactTBD;
} else {
String mapKey = String.format( "%s:%s:%s", artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion() );
if (pomArtifacts.containsKey( mapKey )) {
thePomArtifact = pomArtifacts.get( mapKey );
} else {
thePomArtifact = new DefaultArtifact( artifactTBD.getGroupId(), artifactTBD.getArtifactId(),
artifactTBD.getVersion(), "", "pom", "", new PomArtifactHandler() );
// we resolve the pom file first
HashSet<Artifact> deps = new HashSet<Artifact>();
deps.addAll( project.getDependencyArtifacts() );
deps.add( thePomArtifact );
project.setDependencyArtifacts( deps );
Set<String> scopes = Collections.singleton( Artifact.SCOPE_RUNTIME );
lcdResolver.resolveProjectDependencies( project, scopes, scopes, session, false, Collections.<Artifact>emptySet() );
pomArtifacts.put( mapKey, thePomArtifact );
}
}
if (filterPom) {
filterPom( thePomArtifact );
}
pomFile = thePomArtifact.getFile();
boolean isPomArtifact = "pom".equals( artifactTBD.getType() );
try {
if (isPomArtifact) {
deploy( pomFile, artifactTBD, repo, getLocalRepository() );
} else {
File file = artifactTBD.getFile();
if (file != null && file.isFile()) {
deploy( file, artifactTBD, repo, getLocalRepository() );
} else if (!attachedArtifacts.isEmpty()) {
getLog().info( "No primary artifact to deploy, deploying attached artifacts instead." );
if (updateReleaseInfo) {
thePomArtifact.setRelease( true );
}
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
// propagate the timestamped version to the main artifact for the attached artifacts
// to pick it up
artifactTBD.setResolvedVersion( thePomArtifact.getVersion() );
} else {
String message = "The packaging for this project did not " + "assign a file to the build artifact";
System.err.println( "The artifact on which we crash: " + artifactTBD.getId() );
throw new MojoExecutionException( message );
}
}
if (filterPom) {
deploy( pomFile, thePomArtifact, repo, getLocalRepository() );
}
}
catch (ArtifactDeploymentException e) {
throw new MojoExecutionException( "Failed to deploy artifact", e );
}
}
catch (MojoExecutionException e) {
if (!failureIsAnOption)
throw e;
swallowed++;
getLog().warn( "failed to deploy " + ((Artifact) iter).getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
for (Iterator i = attachedArtifacts.iterator(); i.hasNext(); ) {
Artifact attached = (Artifact) i.next();
try {
deploy( attached.getFile(), attached, repo, getLocalRepository() );
}
catch (ArtifactDeploymentException e) {
if (!failureIsAnOption)
throw new MojoExecutionException( "Failed to deploy artifact", e );
swallowed++;
getLog().warn( "failed to deploy " + attached.getId() + " but continuing anyway " +
"(failureIsAnOption)" );
}
}
if (swallowed > 0) {
getLog().warn( "I swallowed " + swallowed + " deployment exceptions. If you want me to fail on this please" +
" unset failureIsAnOption" );
}
}
|
diff --git a/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/theme/ColorAndStyle.java b/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/theme/ColorAndStyle.java
index a6b5e4805..3449bd371 100644
--- a/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/theme/ColorAndStyle.java
+++ b/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/theme/ColorAndStyle.java
@@ -1,156 +1,158 @@
/*******************************************************************************
* Copyright (c) 2001-2013 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
*******************************************************************************/
package net.sf.robocode.ui.editor.theme;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.robocode.ui.editor.FontStyle;
/**
* Class that is used for maintaining a text color and font style for an editor.
*
* @author Flemming N. Larsen (original)
* @since 1.8.3.0
*/
public class ColorAndStyle {
private final JLabel label;
private final JButton coloredButton;
private final JComboBox fontStyleComboBox;
private final List<IColorAndStyleListener> listeners = new ArrayList<IColorAndStyleListener>();
private Color oldColor;
private FontStyle oldStyle;
public ColorAndStyle(String label, final Color color, final FontStyle fontStyle) {
this.label = new JLabel(label);
coloredButton = createColoredButton(color);
if (coloredButton != null) {
coloredButton.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!coloredButton.getBackground().equals(color)) {
notifyColorChanged(coloredButton.getBackground());
}
}
});
}
fontStyleComboBox = fontStyle == null ? null : ComboBoxUtil.createFontStyleComboBox(fontStyle);
if (fontStyleComboBox != null) {
fontStyleComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- if (fontStyle != FontStyle.fromName((String) fontStyleComboBox.getSelectedItem())) {
- notifyStyleChanged(ComboBoxUtil.getSelectedStyle(fontStyleComboBox));
+ FontStyle newStyle = ComboBoxUtil.getSelectedStyle(fontStyleComboBox);
+ if (oldStyle != newStyle) {
+ notifyStyleChanged(newStyle);
+ oldStyle = newStyle;
}
}
});
}
}
public JLabel getLabel() {
return label;
}
public JButton getColoredButton() {
return coloredButton;
}
public JComboBox getFontStyleComboBox() {
return fontStyleComboBox;
}
public void addListener(IColorAndStyleListener listener) {
listeners.add(listener);
}
public void removeListener(IColorAndStyleListener listener) {
listeners.remove(listener);
}
public Color getSelectedColor() {
return (coloredButton == null) ? null : coloredButton.getBackground();
}
public void setSelectedColor(Color newColor) {
if (coloredButton != null) {
coloredButton.setBackground(newColor);
}
notifyColorChanged(newColor);
}
public FontStyle getSelectedStyle() {
return (fontStyleComboBox == null) ? null : ComboBoxUtil.getSelectedStyle(fontStyleComboBox);
}
public void setSelectedStyle(FontStyle newStyle) {
if (fontStyleComboBox != null) {
ComboBoxUtil.setSelected(fontStyleComboBox, newStyle);
}
notifyStyleChanged(newStyle);
}
private void notifyColorChanged(Color newColor) {
if (newColor != null && !newColor.equals(oldColor)) {
for (IColorAndStyleListener listener : listeners) {
listener.colorChanged(newColor);
}
oldColor = newColor;
}
}
private void notifyStyleChanged(FontStyle newStyle) {
if (newStyle != null && !newStyle.equals(oldStyle)) {
for (IColorAndStyleListener listener : listeners) {
listener.styleChanged(newStyle);
}
oldStyle = newStyle;
}
}
private static JButton createColoredButton(Color color) {
final JButton button = new JButton();
button.setBackground(color);
button.setContentAreaFilled(false);
button.setOpaque(true);
Dimension size = new Dimension(24, 24);
button.setPreferredSize(size);
button.setSize(size);
button.setMaximumSize(size);
button.setMinimumSize(size);
button.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color selectedColor = JColorChooser.showDialog(null, "Pick a color", button.getBackground());
if (selectedColor != null) {
button.setBackground(selectedColor);
}
}
});
return button;
}
}
| true | true |
public ColorAndStyle(String label, final Color color, final FontStyle fontStyle) {
this.label = new JLabel(label);
coloredButton = createColoredButton(color);
if (coloredButton != null) {
coloredButton.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!coloredButton.getBackground().equals(color)) {
notifyColorChanged(coloredButton.getBackground());
}
}
});
}
fontStyleComboBox = fontStyle == null ? null : ComboBoxUtil.createFontStyleComboBox(fontStyle);
if (fontStyleComboBox != null) {
fontStyleComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (fontStyle != FontStyle.fromName((String) fontStyleComboBox.getSelectedItem())) {
notifyStyleChanged(ComboBoxUtil.getSelectedStyle(fontStyleComboBox));
}
}
});
}
}
|
public ColorAndStyle(String label, final Color color, final FontStyle fontStyle) {
this.label = new JLabel(label);
coloredButton = createColoredButton(color);
if (coloredButton != null) {
coloredButton.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!coloredButton.getBackground().equals(color)) {
notifyColorChanged(coloredButton.getBackground());
}
}
});
}
fontStyleComboBox = fontStyle == null ? null : ComboBoxUtil.createFontStyleComboBox(fontStyle);
if (fontStyleComboBox != null) {
fontStyleComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FontStyle newStyle = ComboBoxUtil.getSelectedStyle(fontStyleComboBox);
if (oldStyle != newStyle) {
notifyStyleChanged(newStyle);
oldStyle = newStyle;
}
}
});
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/css/engine/value/css/FontSizeManager.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/css/engine/value/css/FontSizeManager.java
index 99d7589c9..2f8ceaa8e 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/css/engine/value/css/FontSizeManager.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/css/engine/value/css/FontSizeManager.java
@@ -1,208 +1,209 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - modification of Batik's FontSizeManager.java to support BIRT's CSS rules
*******************************************************************************/
package org.eclipse.birt.report.engine.css.engine.value.css;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.css.engine.CSSContext;
import org.eclipse.birt.report.engine.css.engine.CSSEngine;
import org.eclipse.birt.report.engine.css.engine.CSSStylableElement;
import org.eclipse.birt.report.engine.css.engine.ValueManager;
import org.eclipse.birt.report.engine.css.engine.value.AbstractLengthManager;
import org.eclipse.birt.report.engine.css.engine.value.FloatValue;
import org.eclipse.birt.report.engine.css.engine.value.IdentifierManager;
import org.eclipse.birt.report.engine.css.engine.value.StringMap;
import org.eclipse.birt.report.engine.css.engine.value.Value;
import org.w3c.css.sac.LexicalUnit;
import org.w3c.dom.DOMException;
import org.w3c.dom.css.CSSPrimitiveValue;
import org.w3c.dom.css.CSSValue;
/**
* This class provides a manager for the 'font-size' property values.
*
*/
public class FontSizeManager extends AbstractLengthManager {
/**
* The identifier values.
*/
protected final static StringMap values = new StringMap();
static {
values.put(CSSConstants.CSS_LARGE_VALUE, CSSValueConstants.LARGE_VALUE);
values.put(CSSConstants.CSS_LARGER_VALUE, CSSValueConstants.LARGER_VALUE);
values.put(CSSConstants.CSS_MEDIUM_VALUE, CSSValueConstants.MEDIUM_VALUE);
values.put(CSSConstants.CSS_SMALL_VALUE, CSSValueConstants.SMALL_VALUE);
values
.put(CSSConstants.CSS_SMALLER_VALUE,
CSSValueConstants.SMALLER_VALUE);
values
.put(CSSConstants.CSS_X_LARGE_VALUE,
CSSValueConstants.X_LARGE_VALUE);
values
.put(CSSConstants.CSS_X_SMALL_VALUE,
CSSValueConstants.X_SMALL_VALUE);
values.put(CSSConstants.CSS_XX_LARGE_VALUE,
CSSValueConstants.XX_LARGE_VALUE);
values.put(CSSConstants.CSS_XX_SMALL_VALUE,
CSSValueConstants.XX_SMALL_VALUE);
}
/**
* Implements {@link IdentifierManager#getIdentifiers()}.
*/
public StringMap getIdentifiers() {
return values;
}
/**
* Implements {@link ValueManager#isInheritedProperty()}.
*/
public boolean isInheritedProperty() {
return true;
}
/**
* Implements {@link ValueManager#getPropertyName()}.
*/
public String getPropertyName() {
return CSSConstants.CSS_FONT_SIZE_PROPERTY;
}
/**
* Implements {@link ValueManager#getDefaultValue()}.
*/
public Value getDefaultValue() {
return CSSValueConstants.MEDIUM_VALUE;
}
/**
* Implements {@link ValueManager#createValue(LexicalUnit,CSSEngine)}.
*/
public Value createValue(LexicalUnit lu, CSSEngine engine)
throws DOMException {
switch (lu.getLexicalUnitType()) {
case LexicalUnit.SAC_INHERIT:
return CSSValueConstants.INHERIT_VALUE;
case LexicalUnit.SAC_IDENT:
String s = lu.getStringValue().toLowerCase().intern();
Object v = values.get(s);
if (v == null) {
throw createInvalidIdentifierDOMException(s);
}
return (Value) v;
default:
break;
}
return super.createValue(lu, engine);
}
/**
* Implements {@link
* ValueManager#createStringValue(short,String,CSSEngine)}.
*/
public CSSPrimitiveValue createStringValue(short type, String value)
throws DOMException {
if (type != CSSPrimitiveValue.CSS_IDENT) {
throw createInvalidStringTypeDOMException(type);
}
Object v = values.get(value.toLowerCase().intern());
if (v == null) {
throw createInvalidIdentifierDOMException(value);
}
return (CSSPrimitiveValue) v;
}
/**
* Implements {@link
* ValueManager#computeValue(CSSStylableElement,String,CSSEngine,int,StyleMap,Value)}.
*/
public Value computeValue(CSSStylableElement elt, CSSEngine engine,
int idx, Value value) {
CSSContext ctx = engine.getCSSContext();
float fs = ctx.getMediumFontSize();
// absolute size
if (value == CSSValueConstants.XX_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f / 1.2f);
}
if (value == CSSValueConstants.X_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f);
}
if (value == CSSValueConstants.SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs / 1.2f);
}
if (value == CSSValueConstants.MEDIUM_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs);
}
if (value == CSSValueConstants.LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * 1.2f);
}
if (value == CSSValueConstants.X_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f);
}
if (value == CSSValueConstants.XX_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f * 1.2f);
}
float scale = 1.0f;
boolean doParentRelative = false;
// relative size
if (value == CSSValueConstants.SMALLER_VALUE) {
doParentRelative = true;
scale = 1.0f / 1.2f;
} else if (value == CSSValueConstants.LARGER_VALUE) {
doParentRelative = true;
scale = 1.2f;
} else if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
// relative length && percentage
switch (value.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_EMS:
doParentRelative = true;
scale = value.getFloatValue();
break;
case CSSPrimitiveValue.CSS_EXS:
doParentRelative = true;
scale = value.getFloatValue() * 0.5f;
break;
case CSSPrimitiveValue.CSS_PERCENTAGE:
doParentRelative = true;
scale = value.getFloatValue() * 0.01f;
break;
}
}
if (doParentRelative) {
CSSStylableElement parent = (CSSStylableElement) elt.getParent();
if (parent != null) {
IStyle style = parent.getComputedStyle();
if (style != null) {
Value fontSize = (Value)style.getProperty(IStyle.STYLE_FONT_SIZE);
if (fontSize != null) {
fs = fontSize.getFloatValue();
+ return new FloatValue( fontSize.getPrimitiveType( ), fs * scale );
}
}
}
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * scale);
}
if(value.getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER)
{
return super.computeValue(elt, engine, idx, new FloatValue(CSSPrimitiveValue.CSS_PT,
value.getFloatValue()));
}
return super.computeValue(elt, engine, idx, value);
}
}
| true | true |
public Value computeValue(CSSStylableElement elt, CSSEngine engine,
int idx, Value value) {
CSSContext ctx = engine.getCSSContext();
float fs = ctx.getMediumFontSize();
// absolute size
if (value == CSSValueConstants.XX_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f / 1.2f);
}
if (value == CSSValueConstants.X_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f);
}
if (value == CSSValueConstants.SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs / 1.2f);
}
if (value == CSSValueConstants.MEDIUM_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs);
}
if (value == CSSValueConstants.LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * 1.2f);
}
if (value == CSSValueConstants.X_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f);
}
if (value == CSSValueConstants.XX_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f * 1.2f);
}
float scale = 1.0f;
boolean doParentRelative = false;
// relative size
if (value == CSSValueConstants.SMALLER_VALUE) {
doParentRelative = true;
scale = 1.0f / 1.2f;
} else if (value == CSSValueConstants.LARGER_VALUE) {
doParentRelative = true;
scale = 1.2f;
} else if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
// relative length && percentage
switch (value.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_EMS:
doParentRelative = true;
scale = value.getFloatValue();
break;
case CSSPrimitiveValue.CSS_EXS:
doParentRelative = true;
scale = value.getFloatValue() * 0.5f;
break;
case CSSPrimitiveValue.CSS_PERCENTAGE:
doParentRelative = true;
scale = value.getFloatValue() * 0.01f;
break;
}
}
if (doParentRelative) {
CSSStylableElement parent = (CSSStylableElement) elt.getParent();
if (parent != null) {
IStyle style = parent.getComputedStyle();
if (style != null) {
Value fontSize = (Value)style.getProperty(IStyle.STYLE_FONT_SIZE);
if (fontSize != null) {
fs = fontSize.getFloatValue();
}
}
}
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * scale);
}
if(value.getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER)
{
return super.computeValue(elt, engine, idx, new FloatValue(CSSPrimitiveValue.CSS_PT,
value.getFloatValue()));
}
return super.computeValue(elt, engine, idx, value);
}
|
public Value computeValue(CSSStylableElement elt, CSSEngine engine,
int idx, Value value) {
CSSContext ctx = engine.getCSSContext();
float fs = ctx.getMediumFontSize();
// absolute size
if (value == CSSValueConstants.XX_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f / 1.2f);
}
if (value == CSSValueConstants.X_SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs / 1.2f / 1.2f);
}
if (value == CSSValueConstants.SMALL_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs / 1.2f);
}
if (value == CSSValueConstants.MEDIUM_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs);
}
if (value == CSSValueConstants.LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * 1.2f);
}
if (value == CSSValueConstants.X_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f);
}
if (value == CSSValueConstants.XX_LARGE_VALUE) {
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER,
fs * 1.2f * 1.2f * 1.2f);
}
float scale = 1.0f;
boolean doParentRelative = false;
// relative size
if (value == CSSValueConstants.SMALLER_VALUE) {
doParentRelative = true;
scale = 1.0f / 1.2f;
} else if (value == CSSValueConstants.LARGER_VALUE) {
doParentRelative = true;
scale = 1.2f;
} else if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
// relative length && percentage
switch (value.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_EMS:
doParentRelative = true;
scale = value.getFloatValue();
break;
case CSSPrimitiveValue.CSS_EXS:
doParentRelative = true;
scale = value.getFloatValue() * 0.5f;
break;
case CSSPrimitiveValue.CSS_PERCENTAGE:
doParentRelative = true;
scale = value.getFloatValue() * 0.01f;
break;
}
}
if (doParentRelative) {
CSSStylableElement parent = (CSSStylableElement) elt.getParent();
if (parent != null) {
IStyle style = parent.getComputedStyle();
if (style != null) {
Value fontSize = (Value)style.getProperty(IStyle.STYLE_FONT_SIZE);
if (fontSize != null) {
fs = fontSize.getFloatValue();
return new FloatValue( fontSize.getPrimitiveType( ), fs * scale );
}
}
}
return new FloatValue(CSSPrimitiveValue.CSS_NUMBER, fs * scale);
}
if(value.getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER)
{
return super.computeValue(elt, engine, idx, new FloatValue(CSSPrimitiveValue.CSS_PT,
value.getFloatValue()));
}
return super.computeValue(elt, engine, idx, value);
}
|
diff --git a/src/com/android/contacts/activities/PeopleActivity.java b/src/com/android/contacts/activities/PeopleActivity.java
index 464075ae8..92152c8fe 100644
--- a/src/com/android/contacts/activities/PeopleActivity.java
+++ b/src/com/android/contacts/activities/PeopleActivity.java
@@ -1,1742 +1,1745 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.activities;
import com.android.contacts.ContactLoader;
import com.android.contacts.ContactSaveService;
import com.android.contacts.ContactsActivity;
import com.android.contacts.ContactsUtils;
import com.android.contacts.R;
import com.android.contacts.activities.ActionBarAdapter.TabState;
import com.android.contacts.detail.ContactDetailFragment;
import com.android.contacts.detail.ContactDetailLayoutController;
import com.android.contacts.detail.ContactDetailUpdatesFragment;
import com.android.contacts.detail.ContactLoaderFragment;
import com.android.contacts.detail.ContactLoaderFragment.ContactLoaderFragmentListener;
import com.android.contacts.dialog.ClearFrequentsDialog;
import com.android.contacts.group.GroupBrowseListFragment;
import com.android.contacts.group.GroupBrowseListFragment.OnGroupBrowserActionListener;
import com.android.contacts.group.GroupDetailFragment;
import com.android.contacts.interactions.ContactDeletionInteraction;
import com.android.contacts.interactions.ImportExportDialogFragment;
import com.android.contacts.interactions.PhoneNumberInteraction;
import com.android.contacts.list.ContactBrowseListFragment;
import com.android.contacts.list.ContactEntryListFragment;
import com.android.contacts.list.ContactListFilter;
import com.android.contacts.list.ContactListFilterController;
import com.android.contacts.list.ContactTileAdapter.DisplayType;
import com.android.contacts.list.ContactTileFrequentFragment;
import com.android.contacts.list.ContactTileListFragment;
import com.android.contacts.list.ContactsIntentResolver;
import com.android.contacts.list.ContactsRequest;
import com.android.contacts.list.ContactsUnavailableFragment;
import com.android.contacts.list.DefaultContactBrowseListFragment;
import com.android.contacts.list.DirectoryListLoader;
import com.android.contacts.list.OnContactBrowserActionListener;
import com.android.contacts.list.OnContactsUnavailableActionListener;
import com.android.contacts.list.ProviderStatusWatcher;
import com.android.contacts.list.ProviderStatusWatcher.ProviderStatusListener;
import com.android.contacts.model.AccountTypeManager;
import com.android.contacts.model.AccountWithDataSet;
import com.android.contacts.preference.ContactsPreferenceActivity;
import com.android.contacts.preference.DisplayOptionsPreferenceFragment;
import com.android.contacts.util.AccountFilterUtil;
import com.android.contacts.util.AccountPromptUtils;
import com.android.contacts.util.AccountsListAdapter;
import com.android.contacts.util.HelpUtils;
import com.android.contacts.util.UriUtils;
import com.android.contacts.util.AccountsListAdapter.AccountListFilter;
import com.android.contacts.util.Constants;
import com.android.contacts.util.DialogManager;
import com.android.contacts.util.PhoneCapabilityTester;
import com.android.contacts.widget.TransitionAnimationView;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.preference.PreferenceActivity;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.ProviderStatus;
import android.provider.ContactsContract.QuickContact;
import android.provider.Settings;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListPopupWindow;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Displays a list to browse contacts. For xlarge screens, this also displays a detail-pane on
* the right.
*/
public class PeopleActivity extends ContactsActivity
implements View.OnCreateContextMenuListener, ActionBarAdapter.Listener,
DialogManager.DialogShowingViewActivity,
ContactListFilterController.ContactListFilterListener, ProviderStatusListener {
private static final String TAG = "PeopleActivity";
/** Shows a toogle button for hiding/showing updates. Don't submit with true */
private static final boolean DEBUG_TRANSITIONS = false;
// These values needs to start at 2. See {@link ContactEntryListFragment}.
private static final int SUBACTIVITY_NEW_CONTACT = 2;
private static final int SUBACTIVITY_EDIT_CONTACT = 3;
private static final int SUBACTIVITY_NEW_GROUP = 4;
private static final int SUBACTIVITY_EDIT_GROUP = 5;
private static final int SUBACTIVITY_ACCOUNT_FILTER = 6;
private final DialogManager mDialogManager = new DialogManager(this);
private ContactsIntentResolver mIntentResolver;
private ContactsRequest mRequest;
private ActionBarAdapter mActionBarAdapter;
private ContactDetailFragment mContactDetailFragment;
private ContactLoaderFragment mContactDetailLoaderFragment;
private final ContactDetailLoaderFragmentListener mContactDetailLoaderFragmentListener =
new ContactDetailLoaderFragmentListener();
private GroupDetailFragment mGroupDetailFragment;
private final GroupDetailFragmentListener mGroupDetailFragmentListener =
new GroupDetailFragmentListener();
private ContactTileListFragment.Listener mFavoritesFragmentListener =
new StrequentContactListFragmentListener();
private ContactListFilterController mContactListFilterController;
private ContactsUnavailableFragment mContactsUnavailableFragment;
private ProviderStatusWatcher mProviderStatusWatcher;
private int mProviderStatus = -1;
private boolean mOptionsMenuContactsAvailable;
/**
* Showing a list of Contacts. Also used for showing search results in search mode.
*/
private DefaultContactBrowseListFragment mAllFragment;
private ContactTileListFragment mFavoritesFragment;
private ContactTileFrequentFragment mFrequentFragment;
private GroupBrowseListFragment mGroupsFragment;
private View mFavoritesView;
private View mBrowserView;
private TransitionAnimationView mContactDetailsView;
private TransitionAnimationView mGroupDetailsView;
private View mAddGroupImageView;
/** ViewPager for swipe, used only on the phone (i.e. one-pane mode) */
private ViewPager mTabPager;
private TabPagerAdapter mTabPagerAdapter;
private final TabPagerListener mTabPagerListener = new TabPagerListener();
private ContactDetailLayoutController mContactDetailLayoutController;
private final Handler mHandler = new Handler();
/**
* True if this activity instance is a re-created one. i.e. set true after orientation change.
* This is set in {@link #onCreate} for later use in {@link #onStart}.
*/
private boolean mIsRecreatedInstance;
/**
* If {@link #configureFragments(boolean)} is already called. Used to avoid calling it twice
* in {@link #onStart}.
* (This initialization only needs to be done once in onStart() when the Activity was just
* created from scratch -- i.e. onCreate() was just called)
*/
private boolean mFragmentInitialized;
/**
* Whether or not the current contact filter is valid or not. We need to do a check on
* start of the app to verify that the user is not in single contact mode. If so, we should
* dynamically change the filter, unless the incoming intent specifically requested a contact
* that should be displayed in that mode.
*/
private boolean mCurrentFilterIsValid;
/** Sequential ID assigned to each instance; used for logging */
private final int mInstanceId;
private static final AtomicInteger sNextInstanceId = new AtomicInteger();
public PeopleActivity() {
mInstanceId = sNextInstanceId.getAndIncrement();
mIntentResolver = new ContactsIntentResolver(this);
mProviderStatusWatcher = ProviderStatusWatcher.getInstance(this);
}
@Override
public String toString() {
// Shown on logcat
return String.format("%s@%d", getClass().getSimpleName(), mInstanceId);
}
public boolean areContactsAvailable() {
return mProviderStatus == ProviderStatus.STATUS_NORMAL;
}
private boolean areContactWritableAccountsAvailable() {
return ContactsUtils.areContactWritableAccountsAvailable(this);
}
private boolean areGroupWritableAccountsAvailable() {
return ContactsUtils.areGroupWritableAccountsAvailable(this);
}
/**
* Initialize fragments that are (or may not be) in the layout.
*
* For the fragments that are in the layout, we initialize them in
* {@link #createViewsAndFragments(Bundle)} after inflating the layout.
*
* However, there are special fragments which may not be in the layout, so we have to do the
* initialization here.
* The target fragments are:
* - {@link ContactDetailFragment} and {@link ContactDetailUpdatesFragment}: They may not be
* in the layout depending on the configuration. (i.e. portrait)
* - {@link ContactsUnavailableFragment}: We always create it at runtime.
*/
@Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof ContactDetailFragment) {
mContactDetailFragment = (ContactDetailFragment) fragment;
} else if (fragment instanceof ContactsUnavailableFragment) {
mContactsUnavailableFragment = (ContactsUnavailableFragment)fragment;
mContactsUnavailableFragment.setOnContactsUnavailableActionListener(
new ContactsUnavailableFragmentListener());
}
}
@Override
protected void onCreate(Bundle savedState) {
if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
Log.d(Constants.PERFORMANCE_TAG, "PeopleActivity.onCreate start");
}
super.onCreate(savedState);
if (!processIntent(false)) {
finish();
return;
}
mContactListFilterController = ContactListFilterController.getInstance(this);
mContactListFilterController.checkFilterValidity(false);
mContactListFilterController.addListener(this);
mProviderStatusWatcher.addListener(this);
mIsRecreatedInstance = (savedState != null);
createViewsAndFragments(savedState);
if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
Log.d(Constants.PERFORMANCE_TAG, "PeopleActivity.onCreate finish");
}
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
if (!processIntent(true)) {
finish();
return;
}
mActionBarAdapter.initialize(null, mRequest);
mContactListFilterController.checkFilterValidity(false);
mCurrentFilterIsValid = true;
// Re-configure fragments.
configureFragments(true /* from request */);
invalidateOptionsMenuIfNeeded();
}
/**
* Resolve the intent and initialize {@link #mRequest}, and launch another activity if redirect
* is needed.
*
* @param forNewIntent set true if it's called from {@link #onNewIntent(Intent)}.
* @return {@code true} if {@link PeopleActivity} should continue running. {@code false}
* if it shouldn't, in which case the caller should finish() itself and shouldn't do
* farther initialization.
*/
private boolean processIntent(boolean forNewIntent) {
// Extract relevant information from the intent
mRequest = mIntentResolver.resolveIntent(getIntent());
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, this + " processIntent: forNewIntent=" + forNewIntent
+ " intent=" + getIntent() + " request=" + mRequest);
}
if (!mRequest.isValid()) {
setResult(RESULT_CANCELED);
return false;
}
Intent redirect = mRequest.getRedirectIntent();
if (redirect != null) {
// Need to start a different activity
startActivity(redirect);
return false;
}
if (mRequest.getActionCode() == ContactsRequest.ACTION_VIEW_CONTACT
&& !PhoneCapabilityTester.isUsingTwoPanes(this)) {
redirect = new Intent(this, ContactDetailActivity.class);
redirect.setAction(Intent.ACTION_VIEW);
redirect.setData(mRequest.getContactUri());
startActivity(redirect);
return false;
}
setTitle(mRequest.getActivityTitle());
return true;
}
private void createViewsAndFragments(Bundle savedState) {
setContentView(R.layout.people_activity);
final FragmentManager fragmentManager = getFragmentManager();
// Hide all tabs (the current tab will later be reshown once a tab is selected)
final FragmentTransaction transaction = fragmentManager.beginTransaction();
// Prepare the fragments which are used both on 1-pane and on 2-pane.
- boolean isUsingTwoPanes = PhoneCapabilityTester.isUsingTwoPanes(this);
+ final boolean isUsingTwoPanes = PhoneCapabilityTester.isUsingTwoPanes(this);
if (isUsingTwoPanes) {
mFavoritesFragment = getFragment(R.id.favorites_fragment);
mAllFragment = getFragment(R.id.all_fragment);
mGroupsFragment = getFragment(R.id.groups_fragment);
} else {
mTabPager = getView(R.id.tab_pager);
mTabPagerAdapter = new TabPagerAdapter();
mTabPager.setAdapter(mTabPagerAdapter);
mTabPager.setOnPageChangeListener(mTabPagerListener);
final String FAVORITE_TAG = "tab-pager-favorite";
final String ALL_TAG = "tab-pager-all";
final String GROUPS_TAG = "tab-pager-groups";
// Create the fragments and add as children of the view pager.
// The pager adapter will only change the visibility; it'll never create/destroy
// fragments.
// However, if it's after screen rotation, the fragments have been re-created by
// the fragment manager, so first see if there're already the target fragments
// existing.
mFavoritesFragment = (ContactTileListFragment)
fragmentManager.findFragmentByTag(FAVORITE_TAG);
mAllFragment = (DefaultContactBrowseListFragment)
fragmentManager.findFragmentByTag(ALL_TAG);
mGroupsFragment = (GroupBrowseListFragment)
fragmentManager.findFragmentByTag(GROUPS_TAG);
if (mFavoritesFragment == null) {
mFavoritesFragment = new ContactTileListFragment();
mAllFragment = new DefaultContactBrowseListFragment();
mGroupsFragment = new GroupBrowseListFragment();
transaction.add(R.id.tab_pager, mFavoritesFragment, FAVORITE_TAG);
transaction.add(R.id.tab_pager, mAllFragment, ALL_TAG);
transaction.add(R.id.tab_pager, mGroupsFragment, GROUPS_TAG);
}
}
mFavoritesFragment.setListener(mFavoritesFragmentListener);
mAllFragment.setOnContactListActionListener(new ContactBrowserActionListener());
mGroupsFragment.setListener(new GroupBrowserActionListener());
// Hide all fragments for now. We adjust visibility when we get onSelectedTabChanged()
// from ActionBarAdapter.
transaction.hide(mFavoritesFragment);
transaction.hide(mAllFragment);
transaction.hide(mGroupsFragment);
if (isUsingTwoPanes) {
// Prepare 2-pane only fragments/views...
// Container views for fragments
mFavoritesView = getView(R.id.favorites_view);
mContactDetailsView = getView(R.id.contact_details_view);
mGroupDetailsView = getView(R.id.group_details_view);
mBrowserView = getView(R.id.browse_view);
// Only favorites tab with two panes has a separate frequent fragment
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFrequentFragment = getFragment(R.id.frequent_fragment);
mFrequentFragment.setListener(mFavoritesFragmentListener);
mFrequentFragment.setDisplayType(DisplayType.FREQUENT_ONLY);
mFrequentFragment.enableQuickContact(true);
}
mContactDetailLoaderFragment = getFragment(R.id.contact_detail_loader_fragment);
mContactDetailLoaderFragment.setListener(mContactDetailLoaderFragmentListener);
mGroupDetailFragment = getFragment(R.id.group_detail_fragment);
mGroupDetailFragment.setListener(mGroupDetailFragmentListener);
mGroupDetailFragment.setQuickContact(true);
if (mContactDetailFragment != null) {
transaction.hide(mContactDetailFragment);
}
transaction.hide(mGroupDetailFragment);
// Configure contact details
mContactDetailLayoutController = new ContactDetailLayoutController(this, savedState,
getFragmentManager(), mContactDetailsView,
findViewById(R.id.contact_detail_container),
new ContactDetailFragmentListener());
}
transaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
// Setting Properties after fragment is created
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFavoritesFragment.enableQuickContact(true);
mFavoritesFragment.setDisplayType(DisplayType.STARRED_ONLY);
} else {
+ // For 2-pane in All and Groups but not in Favorites fragment, show the chevron
+ // for quick contact popup
+ mFavoritesFragment.enableQuickContact(isUsingTwoPanes);
mFavoritesFragment.setDisplayType(DisplayType.STREQUENT);
}
// Configure action bar
mActionBarAdapter = new ActionBarAdapter(this, this, getActionBar(), isUsingTwoPanes);
mActionBarAdapter.initialize(savedState, mRequest);
invalidateOptionsMenuIfNeeded();
}
@Override
protected void onStart() {
if (!mFragmentInitialized) {
mFragmentInitialized = true;
/* Configure fragments if we haven't.
*
* Note it's a one-shot initialization, so we want to do this in {@link #onCreate}.
*
* However, because this method may indirectly touch views in fragments but fragments
* created in {@link #configureContentView} using a {@link FragmentTransaction} will NOT
* have views until {@link Activity#onCreate} finishes (they would if they were inflated
* from a layout), we need to do it here in {@link #onStart()}.
*
* (When {@link Fragment#onCreateView} is called is different in the former case and
* in the latter case, unfortunately.)
*
* Also, we skip most of the work in it if the activity is a re-created one.
* (so the argument.)
*/
configureFragments(!mIsRecreatedInstance);
} else if (PhoneCapabilityTester.isUsingTwoPanes(this) && !mCurrentFilterIsValid) {
// We only want to do the filter check in onStart for wide screen devices where it
// is often possible to get into single contact mode. Only do this check if
// the filter hasn't already been set properly (i.e. onCreate or onActivityResult).
// Since there is only one {@link ContactListFilterController} across multiple
// activity instances, make sure the filter controller is in sync withthe current
// contact list fragment filter.
// TODO: Clean this up. Perhaps change {@link ContactListFilterController} to not be a
// singleton?
mContactListFilterController.setContactListFilter(mAllFragment.getFilter(), true);
mContactListFilterController.checkFilterValidity(true);
mCurrentFilterIsValid = true;
}
super.onStart();
}
@Override
protected void onPause() {
mOptionsMenuContactsAvailable = false;
mProviderStatus = -1;
mProviderStatusWatcher.stop();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
mProviderStatusWatcher.start();
showContactsUnavailableFragmentIfNecessary();
// Re-register the listener, which may have been cleared when onSaveInstanceState was
// called. See also: onSaveInstanceState
mActionBarAdapter.setListener(this);
if (mTabPager != null) {
mTabPager.setOnPageChangeListener(mTabPagerListener);
}
// Current tab may have changed since the last onSaveInstanceState(). Make sure
// the actual contents match the tab.
updateFragmentsVisibility();
}
@Override
protected void onStop() {
super.onStop();
mCurrentFilterIsValid = false;
}
@Override
protected void onDestroy() {
mProviderStatusWatcher.removeListener(this);
// Some of variables will be null if this Activity redirects Intent.
// See also onCreate() or other methods called during the Activity's initialization.
if (mActionBarAdapter != null) {
mActionBarAdapter.setListener(null);
}
if (mContactListFilterController != null) {
mContactListFilterController.removeListener(this);
}
super.onDestroy();
}
private void configureFragments(boolean fromRequest) {
if (fromRequest) {
ContactListFilter filter = null;
int actionCode = mRequest.getActionCode();
boolean searchMode = mRequest.isSearchMode();
final int tabToOpen;
switch (actionCode) {
case ContactsRequest.ACTION_ALL_CONTACTS:
filter = ContactListFilter.createFilterWithType(
ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS);
tabToOpen = TabState.ALL;
break;
case ContactsRequest.ACTION_CONTACTS_WITH_PHONES:
filter = ContactListFilter.createFilterWithType(
ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY);
tabToOpen = TabState.ALL;
break;
case ContactsRequest.ACTION_FREQUENT:
case ContactsRequest.ACTION_STREQUENT:
case ContactsRequest.ACTION_STARRED:
tabToOpen = TabState.FAVORITES;
break;
case ContactsRequest.ACTION_VIEW_CONTACT:
// We redirect this intent to the detail activity on 1-pane, so we don't get
// here. It's only for 2-pane.
tabToOpen = TabState.ALL;
break;
case ContactsRequest.ACTION_GROUP:
tabToOpen = TabState.GROUPS;
break;
default:
tabToOpen = -1;
break;
}
if (tabToOpen != -1) {
mActionBarAdapter.setCurrentTab(tabToOpen);
}
if (filter != null) {
mContactListFilterController.setContactListFilter(filter, false);
searchMode = false;
}
if (mRequest.getContactUri() != null) {
searchMode = false;
}
mActionBarAdapter.setSearchMode(searchMode);
configureContactListFragmentForRequest();
}
configureContactListFragment();
configureGroupListFragment();
invalidateOptionsMenuIfNeeded();
}
@Override
public void onContactListFilterChanged() {
if (mAllFragment == null || !mAllFragment.isAdded()) {
return;
}
mAllFragment.setFilter(mContactListFilterController.getFilter());
invalidateOptionsMenuIfNeeded();
}
private void setupContactDetailFragment(final Uri contactLookupUri) {
mContactDetailLoaderFragment.loadUri(contactLookupUri);
invalidateOptionsMenuIfNeeded();
}
private void setupGroupDetailFragment(Uri groupUri) {
// If we are switching from one group to another, do a cross-fade
if (mGroupDetailFragment != null && mGroupDetailFragment.getGroupUri() != null &&
!UriUtils.areEqual(mGroupDetailFragment.getGroupUri(), groupUri)) {
mGroupDetailsView.startTransition(mGroupDetailFragment.getView(), false);
}
mGroupDetailFragment.loadGroup(groupUri);
invalidateOptionsMenuIfNeeded();
}
/**
* Handler for action bar actions.
*/
@Override
public void onAction(int action) {
switch (action) {
case ActionBarAdapter.Listener.Action.START_SEARCH_MODE:
// Tell the fragments that we're in the search mode
configureFragments(false /* from request */);
updateFragmentsVisibility();
invalidateOptionsMenu();
break;
case ActionBarAdapter.Listener.Action.STOP_SEARCH_MODE:
setQueryTextToFragment("");
updateFragmentsVisibility();
invalidateOptionsMenu();
break;
case ActionBarAdapter.Listener.Action.CHANGE_SEARCH_QUERY:
setQueryTextToFragment(mActionBarAdapter.getQueryString());
break;
default:
throw new IllegalStateException("Unkonwn ActionBarAdapter action: " + action);
}
}
@Override
public void onSelectedTabChanged() {
updateFragmentsVisibility();
}
/**
* Updates the fragment/view visibility according to the current mode, such as
* {@link ActionBarAdapter#isSearchMode()} and {@link ActionBarAdapter#getCurrentTab()}.
*/
private void updateFragmentsVisibility() {
int tab = mActionBarAdapter.getCurrentTab();
// We use ViewPager on 1-pane.
if (!PhoneCapabilityTester.isUsingTwoPanes(this)) {
if (mActionBarAdapter.isSearchMode()) {
mTabPagerAdapter.setSearchMode(true);
} else {
// No smooth scrolling if quitting from the search mode.
final boolean wasSearchMode = mTabPagerAdapter.isSearchMode();
mTabPagerAdapter.setSearchMode(false);
if (mTabPager.getCurrentItem() != tab) {
mTabPager.setCurrentItem(tab, !wasSearchMode);
}
}
invalidateOptionsMenu();
showEmptyStateForTab(tab);
if (tab == TabState.GROUPS) {
mGroupsFragment.setAddAccountsVisibility(!areGroupWritableAccountsAvailable());
}
return;
}
// for the tablet...
// If in search mode, we use the all list + contact details to show the result.
if (mActionBarAdapter.isSearchMode()) {
tab = TabState.ALL;
}
switch (tab) {
case TabState.FAVORITES:
mFavoritesView.setVisibility(View.VISIBLE);
mBrowserView.setVisibility(View.GONE);
mGroupDetailsView.setVisibility(View.GONE);
mContactDetailsView.setVisibility(View.GONE);
break;
case TabState.GROUPS:
mFavoritesView.setVisibility(View.GONE);
mBrowserView.setVisibility(View.VISIBLE);
mGroupDetailsView.setVisibility(View.VISIBLE);
mContactDetailsView.setVisibility(View.GONE);
mGroupsFragment.setAddAccountsVisibility(!areGroupWritableAccountsAvailable());
break;
case TabState.ALL:
mFavoritesView.setVisibility(View.GONE);
mBrowserView.setVisibility(View.VISIBLE);
mContactDetailsView.setVisibility(View.VISIBLE);
mGroupDetailsView.setVisibility(View.GONE);
break;
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
// Note mContactDetailLoaderFragment is an invisible fragment, but we still have to show/
// hide it so its options menu will be shown/hidden.
switch (tab) {
case TabState.FAVORITES:
showFragment(ft, mFavoritesFragment);
showFragment(ft, mFrequentFragment);
hideFragment(ft, mAllFragment);
hideFragment(ft, mContactDetailLoaderFragment);
hideFragment(ft, mContactDetailFragment);
hideFragment(ft, mGroupsFragment);
hideFragment(ft, mGroupDetailFragment);
break;
case TabState.ALL:
hideFragment(ft, mFavoritesFragment);
hideFragment(ft, mFrequentFragment);
showFragment(ft, mAllFragment);
showFragment(ft, mContactDetailLoaderFragment);
showFragment(ft, mContactDetailFragment);
hideFragment(ft, mGroupsFragment);
hideFragment(ft, mGroupDetailFragment);
break;
case TabState.GROUPS:
hideFragment(ft, mFavoritesFragment);
hideFragment(ft, mFrequentFragment);
hideFragment(ft, mAllFragment);
hideFragment(ft, mContactDetailLoaderFragment);
hideFragment(ft, mContactDetailFragment);
showFragment(ft, mGroupsFragment);
showFragment(ft, mGroupDetailFragment);
break;
}
if (!ft.isEmpty()) {
ft.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
// When switching tabs, we need to invalidate options menu, but executing a
// fragment transaction does it implicitly. We don't have to call invalidateOptionsMenu
// manually.
}
showEmptyStateForTab(tab);
}
private void showEmptyStateForTab(int tab) {
if (mContactsUnavailableFragment != null) {
switch (tab) {
case TabState.FAVORITES:
mContactsUnavailableFragment.setMessageText(
R.string.listTotalAllContactsZeroStarred, -1);
break;
case TabState.GROUPS:
mContactsUnavailableFragment.setMessageText(R.string.noGroups,
areGroupWritableAccountsAvailable() ? -1 : R.string.noAccounts);
break;
case TabState.ALL:
mContactsUnavailableFragment.setMessageText(R.string.noContacts, -1);
break;
}
}
}
private class TabPagerListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Make sure not in the search mode, in which case position != TabState.ordinal().
if (!mTabPagerAdapter.isSearchMode()) {
mActionBarAdapter.setCurrentTab(position, false);
showEmptyStateForTab(position);
if (position == TabState.GROUPS) {
mGroupsFragment.setAddAccountsVisibility(!areGroupWritableAccountsAvailable());
}
invalidateOptionsMenu();
}
}
}
/**
* Adapter for the {@link ViewPager}. Unlike {@link FragmentPagerAdapter},
* {@link #instantiateItem} returns existing fragments, and {@link #instantiateItem}/
* {@link #destroyItem} show/hide fragments instead of attaching/detaching.
*
* In search mode, we always show the "all" fragment, and disable the swipe. We change the
* number of items to 1 to disable the swipe.
*
* TODO figure out a more straight way to disable swipe.
*/
private class TabPagerAdapter extends PagerAdapter {
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private boolean mTabPagerAdapterSearchMode;
private Fragment mCurrentPrimaryItem;
public TabPagerAdapter() {
mFragmentManager = getFragmentManager();
}
public boolean isSearchMode() {
return mTabPagerAdapterSearchMode;
}
public void setSearchMode(boolean searchMode) {
if (searchMode == mTabPagerAdapterSearchMode) {
return;
}
mTabPagerAdapterSearchMode = searchMode;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabPagerAdapterSearchMode ? 1 : TabState.COUNT;
}
/** Gets called when the number of items changes. */
@Override
public int getItemPosition(Object object) {
if (mTabPagerAdapterSearchMode) {
if (object == mAllFragment) {
return 0; // Only 1 page in search mode
}
} else {
if (object == mFavoritesFragment) {
return TabState.FAVORITES;
}
if (object == mAllFragment) {
return TabState.ALL;
}
if (object == mGroupsFragment) {
return TabState.GROUPS;
}
}
return POSITION_NONE;
}
@Override
public void startUpdate(ViewGroup container) {
}
private Fragment getFragment(int position) {
if (mTabPagerAdapterSearchMode) {
if (position == 0) {
return mAllFragment;
}
} else {
if (position == TabState.FAVORITES) {
return mFavoritesFragment;
} else if (position == TabState.ALL) {
return mAllFragment;
} else if (position == TabState.GROUPS) {
return mGroupsFragment;
}
}
throw new IllegalArgumentException("position: " + position);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment f = getFragment(position);
mCurTransaction.show(f);
// Non primary pages are not visible.
f.setUserVisibleHint(f == mCurrentPrimaryItem);
return f;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mCurTransaction.hide((Fragment) object);
}
@Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (mCurrentPrimaryItem != fragment) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setUserVisibleHint(true);
}
mCurrentPrimaryItem = fragment;
}
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
private void setQueryTextToFragment(String query) {
mAllFragment.setQueryString(query, true);
mAllFragment.setVisibleScrollbarEnabled(!mAllFragment.isSearchMode());
}
private void configureContactListFragmentForRequest() {
Uri contactUri = mRequest.getContactUri();
if (contactUri != null) {
// For an incoming request, explicitly require a selection if we are on 2-pane UI,
// (i.e. even if we view the same selected contact, the contact may no longer be
// in the list, so we must refresh the list).
if (PhoneCapabilityTester.isUsingTwoPanes(this)) {
mAllFragment.setSelectionRequired(true);
}
mAllFragment.setSelectedContactUri(contactUri);
}
mAllFragment.setFilter(mContactListFilterController.getFilter());
setQueryTextToFragment(mActionBarAdapter.getQueryString());
if (mRequest.isDirectorySearchEnabled()) {
mAllFragment.setDirectorySearchMode(DirectoryListLoader.SEARCH_MODE_DEFAULT);
} else {
mAllFragment.setDirectorySearchMode(DirectoryListLoader.SEARCH_MODE_NONE);
}
}
private void configureContactListFragment() {
// Filter may be changed when this Activity is in background.
mAllFragment.setFilter(mContactListFilterController.getFilter());
final boolean useTwoPane = PhoneCapabilityTester.isUsingTwoPanes(this);
mAllFragment.setVerticalScrollbarPosition(
useTwoPane
? View.SCROLLBAR_POSITION_LEFT
: View.SCROLLBAR_POSITION_RIGHT);
mAllFragment.setSelectionVisible(useTwoPane);
mAllFragment.setQuickContactEnabled(!useTwoPane);
}
private void configureGroupListFragment() {
final boolean useTwoPane = PhoneCapabilityTester.isUsingTwoPanes(this);
mGroupsFragment.setVerticalScrollbarPosition(
useTwoPane
? View.SCROLLBAR_POSITION_LEFT
: View.SCROLLBAR_POSITION_RIGHT);
mGroupsFragment.setSelectionVisible(useTwoPane);
}
@Override
public void onProviderStatusChange() {
showContactsUnavailableFragmentIfNecessary();
}
private void showContactsUnavailableFragmentIfNecessary() {
int providerStatus = mProviderStatusWatcher.getProviderStatus();
if (providerStatus == mProviderStatus) {
return;
}
mProviderStatus = providerStatus;
View contactsUnavailableView = findViewById(R.id.contacts_unavailable_view);
View mainView = findViewById(R.id.main_view);
if (mProviderStatus == ProviderStatus.STATUS_NORMAL) {
// Ensure that the mTabPager is visible; we may have made it invisible below.
contactsUnavailableView.setVisibility(View.GONE);
if (mTabPager != null) {
mTabPager.setVisibility(View.VISIBLE);
}
if (mainView != null) {
mainView.setVisibility(View.VISIBLE);
}
if (mAllFragment != null) {
mAllFragment.setEnabled(true);
}
} else {
// If there are no accounts on the device and we should show the "no account" prompt
// (based on {@link SharedPreferences}), then launch the account setup activity so the
// user can sign-in or create an account.
if (!areContactWritableAccountsAvailable() &&
AccountPromptUtils.shouldShowAccountPrompt(this)) {
AccountPromptUtils.launchAccountPrompt(this);
return;
}
// Otherwise, continue setting up the page so that the user can still use the app
// without an account.
if (mAllFragment != null) {
mAllFragment.setEnabled(false);
}
if (mContactsUnavailableFragment == null) {
mContactsUnavailableFragment = new ContactsUnavailableFragment();
mContactsUnavailableFragment.setOnContactsUnavailableActionListener(
new ContactsUnavailableFragmentListener());
getFragmentManager().beginTransaction()
.replace(R.id.contacts_unavailable_container, mContactsUnavailableFragment)
.commitAllowingStateLoss();
} else {
mContactsUnavailableFragment.update();
}
// Show the contactsUnavailableView, and hide the mTabPager so that we don't
// see it sliding in underneath the contactsUnavailableView at the edges.
contactsUnavailableView.setVisibility(View.VISIBLE);
if (mTabPager != null) {
mTabPager.setVisibility(View.GONE);
}
if (mainView != null) {
mainView.setVisibility(View.INVISIBLE);
}
showEmptyStateForTab(mActionBarAdapter.getCurrentTab());
}
invalidateOptionsMenuIfNeeded();
}
private final class ContactBrowserActionListener implements OnContactBrowserActionListener {
@Override
public void onSelectionChange() {
if (PhoneCapabilityTester.isUsingTwoPanes(PeopleActivity.this)) {
setupContactDetailFragment(mAllFragment.getSelectedContactUri());
}
}
@Override
public void onViewContactAction(Uri contactLookupUri) {
if (PhoneCapabilityTester.isUsingTwoPanes(PeopleActivity.this)) {
setupContactDetailFragment(contactLookupUri);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, contactLookupUri);
startActivity(intent);
}
}
@Override
public void onCreateNewContactAction() {
Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
Bundle extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
startActivity(intent);
}
@Override
public void onEditContactAction(Uri contactLookupUri) {
Intent intent = new Intent(Intent.ACTION_EDIT, contactLookupUri);
Bundle extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
intent.putExtra(
ContactEditorActivity.INTENT_KEY_FINISH_ACTIVITY_ON_SAVE_COMPLETED, true);
startActivityForResult(intent, SUBACTIVITY_EDIT_CONTACT);
}
@Override
public void onAddToFavoritesAction(Uri contactUri) {
ContentValues values = new ContentValues(1);
values.put(Contacts.STARRED, 1);
getContentResolver().update(contactUri, values, null, null);
}
@Override
public void onRemoveFromFavoritesAction(Uri contactUri) {
ContentValues values = new ContentValues(1);
values.put(Contacts.STARRED, 0);
getContentResolver().update(contactUri, values, null, null);
}
@Override
public void onCallContactAction(Uri contactUri) {
PhoneNumberInteraction.startInteractionForPhoneCall(PeopleActivity.this, contactUri);
}
@Override
public void onSmsContactAction(Uri contactUri) {
PhoneNumberInteraction.startInteractionForTextMessage(PeopleActivity.this, contactUri);
}
@Override
public void onDeleteContactAction(Uri contactUri) {
ContactDeletionInteraction.start(PeopleActivity.this, contactUri, false);
}
@Override
public void onFinishAction() {
onBackPressed();
}
@Override
public void onInvalidSelection() {
ContactListFilter filter;
ContactListFilter currentFilter = mAllFragment.getFilter();
if (currentFilter != null
&& currentFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
filter = ContactListFilter.createFilterWithType(
ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS);
mAllFragment.setFilter(filter);
} else {
filter = ContactListFilter.createFilterWithType(
ContactListFilter.FILTER_TYPE_SINGLE_CONTACT);
mAllFragment.setFilter(filter, false);
}
mContactListFilterController.setContactListFilter(filter, true);
}
}
private class ContactDetailLoaderFragmentListener implements ContactLoaderFragmentListener {
@Override
public void onContactNotFound() {
// Nothing needs to be done here
}
@Override
public void onDetailsLoaded(final ContactLoader.Result result) {
if (result == null) {
// Nothing is loaded. Show empty state.
mContactDetailLayoutController.showEmptyState();
return;
}
// Since {@link FragmentTransaction}s cannot be done in the onLoadFinished() of the
// {@link LoaderCallbacks}, then post this {@link Runnable} to the {@link Handler}
// on the main thread to execute later.
mHandler.post(new Runnable() {
@Override
public void run() {
// If the activity is destroyed (or will be destroyed soon), don't update the UI
if (isFinishing()) {
return;
}
mContactDetailLayoutController.setContactData(result);
}
});
}
@Override
public void onEditRequested(Uri contactLookupUri) {
Intent intent = new Intent(Intent.ACTION_EDIT, contactLookupUri);
intent.putExtra(
ContactEditorActivity.INTENT_KEY_FINISH_ACTIVITY_ON_SAVE_COMPLETED, true);
startActivityForResult(intent, SUBACTIVITY_EDIT_CONTACT);
}
@Override
public void onDeleteRequested(Uri contactUri) {
ContactDeletionInteraction.start(PeopleActivity.this, contactUri, false);
}
}
public class ContactDetailFragmentListener implements ContactDetailFragment.Listener {
@Override
public void onItemClicked(Intent intent) {
if (intent == null) {
return;
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found for intent: " + intent);
}
}
@Override
public void onCreateRawContactRequested(ArrayList<ContentValues> values,
AccountWithDataSet account) {
Toast.makeText(PeopleActivity.this, R.string.toast_making_personal_copy,
Toast.LENGTH_LONG).show();
Intent serviceIntent = ContactSaveService.createNewRawContactIntent(
PeopleActivity.this, values, account,
PeopleActivity.class, Intent.ACTION_VIEW);
startService(serviceIntent);
}
}
private class ContactsUnavailableFragmentListener
implements OnContactsUnavailableActionListener {
@Override
public void onCreateNewContactAction() {
startActivity(new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI));
}
@Override
public void onAddAccountAction() {
Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Settings.EXTRA_AUTHORITIES,
new String[] { ContactsContract.AUTHORITY });
startActivity(intent);
}
@Override
public void onImportContactsFromFileAction() {
ImportExportDialogFragment.show(getFragmentManager(), areContactsAvailable());
}
@Override
public void onFreeInternalStorageAction() {
startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));
}
}
private final class StrequentContactListFragmentListener
implements ContactTileListFragment.Listener {
@Override
public void onContactSelected(Uri contactUri, Rect targetRect) {
if (PhoneCapabilityTester.isUsingTwoPanes(PeopleActivity.this)) {
QuickContact.showQuickContact(PeopleActivity.this, targetRect, contactUri, 0, null);
} else {
startActivity(new Intent(Intent.ACTION_VIEW, contactUri));
}
}
@Override
public void onCallNumberDirectly(String phoneNumber) {
// No need to call phone number directly from People app.
Log.w(TAG, "unexpected invocation of onCallNumberDirectly()");
}
}
private final class GroupBrowserActionListener implements OnGroupBrowserActionListener {
@Override
public void onViewGroupAction(Uri groupUri) {
if (PhoneCapabilityTester.isUsingTwoPanes(PeopleActivity.this)) {
setupGroupDetailFragment(groupUri);
} else {
Intent intent = new Intent(PeopleActivity.this, GroupDetailActivity.class);
intent.setData(groupUri);
startActivity(intent);
}
}
}
private class GroupDetailFragmentListener implements GroupDetailFragment.Listener {
@Override
public void onGroupSizeUpdated(String size) {
// Nothing needs to be done here because the size will be displayed in the detail
// fragment
}
@Override
public void onGroupTitleUpdated(String title) {
// Nothing needs to be done here because the title will be displayed in the detail
// fragment
}
@Override
public void onAccountTypeUpdated(String accountTypeString, String dataSet) {
// Nothing needs to be done here because the group source will be displayed in the
// detail fragment
}
@Override
public void onEditRequested(Uri groupUri) {
final Intent intent = new Intent(PeopleActivity.this, GroupEditorActivity.class);
intent.setData(groupUri);
intent.setAction(Intent.ACTION_EDIT);
startActivityForResult(intent, SUBACTIVITY_EDIT_GROUP);
}
@Override
public void onContactSelected(Uri contactUri) {
// Nothing needs to be done here because either quickcontact will be displayed
// or activity will take care of selection
}
}
public void startActivityAndForwardResult(final Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
// Forward extras to the new activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
startActivity(intent);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!areContactsAvailable()) {
// If contacts aren't available, hide all menu items.
return false;
}
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.people_options, menu);
// On narrow screens we specify a NEW group button in the {@link ActionBar}, so that
// it can be in the overflow menu. On wide screens, we use a custom view because we need
// its location for anchoring the account-selector popup.
final MenuItem addGroup = menu.findItem(R.id.menu_custom_add_group);
if (addGroup != null) {
mAddGroupImageView = getLayoutInflater().inflate(
R.layout.add_group_menu_item, null, false);
mAddGroupImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
createNewGroupWithAccountDisambiguation();
}
});
addGroup.setActionView(mAddGroupImageView);
}
if (DEBUG_TRANSITIONS && mContactDetailLoaderFragment != null) {
final MenuItem toggleSocial =
menu.add(mContactDetailLoaderFragment.getLoadStreamItems() ? "less" : "more");
toggleSocial.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
toggleSocial.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
mContactDetailLoaderFragment.toggleLoadStreamItems();
invalidateOptionsMenu();
return false;
}
});
}
return true;
}
private void invalidateOptionsMenuIfNeeded() {
if (isOptionsMenuChanged()) {
invalidateOptionsMenu();
}
}
public boolean isOptionsMenuChanged() {
if (mOptionsMenuContactsAvailable != areContactsAvailable()) {
return true;
}
if (mAllFragment != null && mAllFragment.isOptionsMenuChanged()) {
return true;
}
if (mContactDetailLoaderFragment != null &&
mContactDetailLoaderFragment.isOptionsMenuChanged()) {
return true;
}
if (mGroupDetailFragment != null && mGroupDetailFragment.isOptionsMenuChanged()) {
return true;
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mOptionsMenuContactsAvailable = areContactsAvailable();
if (!mOptionsMenuContactsAvailable) {
return false;
}
// Get references to individual menu items in the menu
final MenuItem addContactMenu = menu.findItem(R.id.menu_add_contact);
final MenuItem contactsFilterMenu = menu.findItem(R.id.menu_contacts_filter);
MenuItem addGroupMenu = menu.findItem(R.id.menu_add_group);
if (addGroupMenu == null) {
addGroupMenu = menu.findItem(R.id.menu_custom_add_group);
}
final MenuItem clearFrequentsMenu = menu.findItem(R.id.menu_clear_frequents);
final MenuItem helpMenu = menu.findItem(R.id.menu_help);
final boolean isSearchMode = mActionBarAdapter.isSearchMode();
if (isSearchMode) {
addContactMenu.setVisible(false);
addGroupMenu.setVisible(false);
contactsFilterMenu.setVisible(false);
clearFrequentsMenu.setVisible(false);
helpMenu.setVisible(false);
} else {
switch (mActionBarAdapter.getCurrentTab()) {
case TabState.FAVORITES:
addContactMenu.setVisible(false);
addGroupMenu.setVisible(false);
contactsFilterMenu.setVisible(false);
clearFrequentsMenu.setVisible(hasFrequents());
break;
case TabState.ALL:
addContactMenu.setVisible(true);
addGroupMenu.setVisible(false);
contactsFilterMenu.setVisible(true);
clearFrequentsMenu.setVisible(false);
break;
case TabState.GROUPS:
// Do not display the "new group" button if no accounts are available
if (areGroupWritableAccountsAvailable()) {
addGroupMenu.setVisible(true);
} else {
addGroupMenu.setVisible(false);
}
addContactMenu.setVisible(false);
contactsFilterMenu.setVisible(false);
clearFrequentsMenu.setVisible(false);
break;
}
HelpUtils.prepareHelpMenuItem(this, helpMenu, R.string.help_url_people_main);
}
final boolean showMiscOptions = !isSearchMode;
makeMenuItemVisible(menu, R.id.menu_search, showMiscOptions);
makeMenuItemVisible(menu, R.id.menu_import_export, showMiscOptions);
makeMenuItemVisible(menu, R.id.menu_accounts, showMiscOptions);
makeMenuItemVisible(menu, R.id.menu_settings,
showMiscOptions && !ContactsPreferenceActivity.isEmpty(this));
return true;
}
/**
* Returns whether there are any frequently contacted people being displayed
* @return
*/
private boolean hasFrequents() {
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
return mFrequentFragment.hasFrequents();
} else {
return mFavoritesFragment.hasFrequents();
}
}
private void makeMenuItemVisible(Menu menu, int itemId, boolean visible) {
MenuItem item =menu.findItem(itemId);
if (item != null) {
item.setVisible(visible);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
// The home icon on the action bar is pressed
if (mActionBarAdapter.isUpShowing()) {
// "UP" icon press -- should be treated as "back".
onBackPressed();
}
return true;
}
case R.id.menu_settings: {
final Intent intent = new Intent(this, ContactsPreferenceActivity.class);
// as there is only one section right now, make sure it is selected
// on small screens, this also hides the section selector
// Due to b/5045558, this code unfortunately only works properly on phones
boolean settingsAreMultiPane = getResources().getBoolean(
com.android.internal.R.bool.preferences_prefer_dual_pane);
if (!settingsAreMultiPane) {
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
DisplayOptionsPreferenceFragment.class.getName());
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT_TITLE,
R.string.preference_displayOptions);
}
startActivity(intent);
return true;
}
case R.id.menu_contacts_filter: {
AccountFilterUtil.startAccountFilterActivityForResult(
this, SUBACTIVITY_ACCOUNT_FILTER,
mContactListFilterController.getFilter());
return true;
}
case R.id.menu_search: {
onSearchRequested();
return true;
}
case R.id.menu_add_contact: {
final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
// On 2-pane UI, we can let the editor activity finish itself and return
// to this activity to display the new contact.
if (PhoneCapabilityTester.isUsingTwoPanes(this)) {
intent.putExtra(
ContactEditorActivity.INTENT_KEY_FINISH_ACTIVITY_ON_SAVE_COMPLETED, true);
startActivityForResult(intent, SUBACTIVITY_NEW_CONTACT);
} else {
// Otherwise, on 1-pane UI, we need the editor to launch the view contact
// intent itself.
startActivity(intent);
}
return true;
}
case R.id.menu_add_group: {
createNewGroupWithAccountDisambiguation();
return true;
}
case R.id.menu_import_export: {
ImportExportDialogFragment.show(getFragmentManager(), areContactsAvailable());
return true;
}
case R.id.menu_clear_frequents: {
ClearFrequentsDialog.show(getFragmentManager());
return true;
}
case R.id.menu_accounts: {
final Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] {
ContactsContract.AUTHORITY
});
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
return true;
}
}
return false;
}
private void createNewGroupWithAccountDisambiguation() {
final List<AccountWithDataSet> accounts =
AccountTypeManager.getInstance(this).getAccounts(true);
if (accounts.size() <= 1 || mAddGroupImageView == null) {
// No account to choose or no control to anchor the popup-menu to
// ==> just go straight to the editor which will disambig if necessary
final Intent intent = new Intent(this, GroupEditorActivity.class);
intent.setAction(Intent.ACTION_INSERT);
startActivityForResult(intent, SUBACTIVITY_NEW_GROUP);
return;
}
final ListPopupWindow popup = new ListPopupWindow(this, null);
popup.setWidth(getResources().getDimensionPixelSize(R.dimen.account_selector_popup_width));
popup.setAnchorView(mAddGroupImageView);
// Create a list adapter with all writeable accounts (assume that the writeable accounts all
// allow group creation).
final AccountsListAdapter adapter = new AccountsListAdapter(this,
AccountListFilter.ACCOUNTS_GROUP_WRITABLE);
popup.setAdapter(adapter);
popup.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
popup.dismiss();
AccountWithDataSet account = adapter.getItem(position);
final Intent intent = new Intent(PeopleActivity.this, GroupEditorActivity.class);
intent.setAction(Intent.ACTION_INSERT);
intent.putExtra(Intents.Insert.ACCOUNT, account);
intent.putExtra(Intents.Insert.DATA_SET, account.dataSet);
startActivityForResult(intent, SUBACTIVITY_NEW_GROUP);
}
});
popup.setModal(true);
popup.show();
}
@Override
public boolean onSearchRequested() { // Search key pressed.
mActionBarAdapter.setSearchMode(true);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SUBACTIVITY_ACCOUNT_FILTER: {
AccountFilterUtil.handleAccountFilterResult(
mContactListFilterController, resultCode, data);
break;
}
case SUBACTIVITY_NEW_CONTACT:
case SUBACTIVITY_EDIT_CONTACT: {
if (resultCode == RESULT_OK && PhoneCapabilityTester.isUsingTwoPanes(this)) {
mRequest.setActionCode(ContactsRequest.ACTION_VIEW_CONTACT);
mAllFragment.setSelectionRequired(true);
mAllFragment.setSelectedContactUri(data.getData());
// Suppress IME if in search mode
if (mActionBarAdapter != null) {
mActionBarAdapter.clearFocusOnSearchView();
}
// No need to change the contact filter
mCurrentFilterIsValid = true;
}
break;
}
case SUBACTIVITY_NEW_GROUP:
case SUBACTIVITY_EDIT_GROUP: {
if (resultCode == RESULT_OK && PhoneCapabilityTester.isUsingTwoPanes(this)) {
mRequest.setActionCode(ContactsRequest.ACTION_GROUP);
mGroupsFragment.setSelectedUri(data.getData());
}
break;
}
// TODO: Using the new startActivityWithResultFromFragment API this should not be needed
// anymore
case ContactEntryListFragment.ACTIVITY_REQUEST_CODE_PICKER:
if (resultCode == RESULT_OK) {
mAllFragment.onPickerResult(data);
}
// TODO fix or remove multipicker code
// else if (resultCode == RESULT_CANCELED && mMode == MODE_PICK_MULTIPLE_PHONES) {
// // Finish the activity if the sub activity was canceled as back key is used
// // to confirm user selection in MODE_PICK_MULTIPLE_PHONES.
// finish();
// }
// break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO move to the fragment
switch (keyCode) {
// case KeyEvent.KEYCODE_CALL: {
// if (callSelection()) {
// return true;
// }
// break;
// }
case KeyEvent.KEYCODE_DEL: {
if (deleteSelection()) {
return true;
}
break;
}
default: {
// Bring up the search UI if the user starts typing
final int unicodeChar = event.getUnicodeChar();
if ((unicodeChar != 0)
// If COMBINING_ACCENT is set, it's not a unicode character.
&& ((unicodeChar & KeyCharacterMap.COMBINING_ACCENT) == 0)
&& !Character.isWhitespace(unicodeChar)) {
String query = new String(new int[]{ unicodeChar }, 0, 1);
if (!mActionBarAdapter.isSearchMode()) {
mActionBarAdapter.setQueryString(query);
mActionBarAdapter.setSearchMode(true);
return true;
}
}
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
if (mActionBarAdapter.isSearchMode()) {
mActionBarAdapter.setSearchMode(false);
} else {
super.onBackPressed();
}
}
private boolean deleteSelection() {
// TODO move to the fragment
// if (mActionCode == ContactsRequest.ACTION_DEFAULT) {
// final int position = mListView.getSelectedItemPosition();
// if (position != ListView.INVALID_POSITION) {
// Uri contactUri = getContactUri(position);
// if (contactUri != null) {
// doContactDelete(contactUri);
// return true;
// }
// }
// }
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mActionBarAdapter.onSaveInstanceState(outState);
if (mContactDetailLayoutController != null) {
mContactDetailLayoutController.onSaveInstanceState(outState);
}
// Clear the listener to make sure we don't get callbacks after onSaveInstanceState,
// in order to avoid doing fragment transactions after it.
// TODO Figure out a better way to deal with the issue.
mActionBarAdapter.setListener(null);
if (mTabPager != null) {
mTabPager.setOnPageChangeListener(null);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// In our own lifecycle, the focus is saved and restore but later taken away by the
// ViewPager. As a hack, we force focus on the SearchView if we know that we are searching.
// This fixes the keyboard going away on screen rotation
if (mActionBarAdapter.isSearchMode()) {
mActionBarAdapter.setFocusOnSearchView();
}
}
@Override
public DialogManager getDialogManager() {
return mDialogManager;
}
// Visible for testing
public ContactBrowseListFragment getListFragment() {
return mAllFragment;
}
// Visible for testing
public ContactDetailFragment getDetailFragment() {
return mContactDetailFragment;
}
}
| false | true |
private void createViewsAndFragments(Bundle savedState) {
setContentView(R.layout.people_activity);
final FragmentManager fragmentManager = getFragmentManager();
// Hide all tabs (the current tab will later be reshown once a tab is selected)
final FragmentTransaction transaction = fragmentManager.beginTransaction();
// Prepare the fragments which are used both on 1-pane and on 2-pane.
boolean isUsingTwoPanes = PhoneCapabilityTester.isUsingTwoPanes(this);
if (isUsingTwoPanes) {
mFavoritesFragment = getFragment(R.id.favorites_fragment);
mAllFragment = getFragment(R.id.all_fragment);
mGroupsFragment = getFragment(R.id.groups_fragment);
} else {
mTabPager = getView(R.id.tab_pager);
mTabPagerAdapter = new TabPagerAdapter();
mTabPager.setAdapter(mTabPagerAdapter);
mTabPager.setOnPageChangeListener(mTabPagerListener);
final String FAVORITE_TAG = "tab-pager-favorite";
final String ALL_TAG = "tab-pager-all";
final String GROUPS_TAG = "tab-pager-groups";
// Create the fragments and add as children of the view pager.
// The pager adapter will only change the visibility; it'll never create/destroy
// fragments.
// However, if it's after screen rotation, the fragments have been re-created by
// the fragment manager, so first see if there're already the target fragments
// existing.
mFavoritesFragment = (ContactTileListFragment)
fragmentManager.findFragmentByTag(FAVORITE_TAG);
mAllFragment = (DefaultContactBrowseListFragment)
fragmentManager.findFragmentByTag(ALL_TAG);
mGroupsFragment = (GroupBrowseListFragment)
fragmentManager.findFragmentByTag(GROUPS_TAG);
if (mFavoritesFragment == null) {
mFavoritesFragment = new ContactTileListFragment();
mAllFragment = new DefaultContactBrowseListFragment();
mGroupsFragment = new GroupBrowseListFragment();
transaction.add(R.id.tab_pager, mFavoritesFragment, FAVORITE_TAG);
transaction.add(R.id.tab_pager, mAllFragment, ALL_TAG);
transaction.add(R.id.tab_pager, mGroupsFragment, GROUPS_TAG);
}
}
mFavoritesFragment.setListener(mFavoritesFragmentListener);
mAllFragment.setOnContactListActionListener(new ContactBrowserActionListener());
mGroupsFragment.setListener(new GroupBrowserActionListener());
// Hide all fragments for now. We adjust visibility when we get onSelectedTabChanged()
// from ActionBarAdapter.
transaction.hide(mFavoritesFragment);
transaction.hide(mAllFragment);
transaction.hide(mGroupsFragment);
if (isUsingTwoPanes) {
// Prepare 2-pane only fragments/views...
// Container views for fragments
mFavoritesView = getView(R.id.favorites_view);
mContactDetailsView = getView(R.id.contact_details_view);
mGroupDetailsView = getView(R.id.group_details_view);
mBrowserView = getView(R.id.browse_view);
// Only favorites tab with two panes has a separate frequent fragment
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFrequentFragment = getFragment(R.id.frequent_fragment);
mFrequentFragment.setListener(mFavoritesFragmentListener);
mFrequentFragment.setDisplayType(DisplayType.FREQUENT_ONLY);
mFrequentFragment.enableQuickContact(true);
}
mContactDetailLoaderFragment = getFragment(R.id.contact_detail_loader_fragment);
mContactDetailLoaderFragment.setListener(mContactDetailLoaderFragmentListener);
mGroupDetailFragment = getFragment(R.id.group_detail_fragment);
mGroupDetailFragment.setListener(mGroupDetailFragmentListener);
mGroupDetailFragment.setQuickContact(true);
if (mContactDetailFragment != null) {
transaction.hide(mContactDetailFragment);
}
transaction.hide(mGroupDetailFragment);
// Configure contact details
mContactDetailLayoutController = new ContactDetailLayoutController(this, savedState,
getFragmentManager(), mContactDetailsView,
findViewById(R.id.contact_detail_container),
new ContactDetailFragmentListener());
}
transaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
// Setting Properties after fragment is created
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFavoritesFragment.enableQuickContact(true);
mFavoritesFragment.setDisplayType(DisplayType.STARRED_ONLY);
} else {
mFavoritesFragment.setDisplayType(DisplayType.STREQUENT);
}
// Configure action bar
mActionBarAdapter = new ActionBarAdapter(this, this, getActionBar(), isUsingTwoPanes);
mActionBarAdapter.initialize(savedState, mRequest);
invalidateOptionsMenuIfNeeded();
}
|
private void createViewsAndFragments(Bundle savedState) {
setContentView(R.layout.people_activity);
final FragmentManager fragmentManager = getFragmentManager();
// Hide all tabs (the current tab will later be reshown once a tab is selected)
final FragmentTransaction transaction = fragmentManager.beginTransaction();
// Prepare the fragments which are used both on 1-pane and on 2-pane.
final boolean isUsingTwoPanes = PhoneCapabilityTester.isUsingTwoPanes(this);
if (isUsingTwoPanes) {
mFavoritesFragment = getFragment(R.id.favorites_fragment);
mAllFragment = getFragment(R.id.all_fragment);
mGroupsFragment = getFragment(R.id.groups_fragment);
} else {
mTabPager = getView(R.id.tab_pager);
mTabPagerAdapter = new TabPagerAdapter();
mTabPager.setAdapter(mTabPagerAdapter);
mTabPager.setOnPageChangeListener(mTabPagerListener);
final String FAVORITE_TAG = "tab-pager-favorite";
final String ALL_TAG = "tab-pager-all";
final String GROUPS_TAG = "tab-pager-groups";
// Create the fragments and add as children of the view pager.
// The pager adapter will only change the visibility; it'll never create/destroy
// fragments.
// However, if it's after screen rotation, the fragments have been re-created by
// the fragment manager, so first see if there're already the target fragments
// existing.
mFavoritesFragment = (ContactTileListFragment)
fragmentManager.findFragmentByTag(FAVORITE_TAG);
mAllFragment = (DefaultContactBrowseListFragment)
fragmentManager.findFragmentByTag(ALL_TAG);
mGroupsFragment = (GroupBrowseListFragment)
fragmentManager.findFragmentByTag(GROUPS_TAG);
if (mFavoritesFragment == null) {
mFavoritesFragment = new ContactTileListFragment();
mAllFragment = new DefaultContactBrowseListFragment();
mGroupsFragment = new GroupBrowseListFragment();
transaction.add(R.id.tab_pager, mFavoritesFragment, FAVORITE_TAG);
transaction.add(R.id.tab_pager, mAllFragment, ALL_TAG);
transaction.add(R.id.tab_pager, mGroupsFragment, GROUPS_TAG);
}
}
mFavoritesFragment.setListener(mFavoritesFragmentListener);
mAllFragment.setOnContactListActionListener(new ContactBrowserActionListener());
mGroupsFragment.setListener(new GroupBrowserActionListener());
// Hide all fragments for now. We adjust visibility when we get onSelectedTabChanged()
// from ActionBarAdapter.
transaction.hide(mFavoritesFragment);
transaction.hide(mAllFragment);
transaction.hide(mGroupsFragment);
if (isUsingTwoPanes) {
// Prepare 2-pane only fragments/views...
// Container views for fragments
mFavoritesView = getView(R.id.favorites_view);
mContactDetailsView = getView(R.id.contact_details_view);
mGroupDetailsView = getView(R.id.group_details_view);
mBrowserView = getView(R.id.browse_view);
// Only favorites tab with two panes has a separate frequent fragment
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFrequentFragment = getFragment(R.id.frequent_fragment);
mFrequentFragment.setListener(mFavoritesFragmentListener);
mFrequentFragment.setDisplayType(DisplayType.FREQUENT_ONLY);
mFrequentFragment.enableQuickContact(true);
}
mContactDetailLoaderFragment = getFragment(R.id.contact_detail_loader_fragment);
mContactDetailLoaderFragment.setListener(mContactDetailLoaderFragmentListener);
mGroupDetailFragment = getFragment(R.id.group_detail_fragment);
mGroupDetailFragment.setListener(mGroupDetailFragmentListener);
mGroupDetailFragment.setQuickContact(true);
if (mContactDetailFragment != null) {
transaction.hide(mContactDetailFragment);
}
transaction.hide(mGroupDetailFragment);
// Configure contact details
mContactDetailLayoutController = new ContactDetailLayoutController(this, savedState,
getFragmentManager(), mContactDetailsView,
findViewById(R.id.contact_detail_container),
new ContactDetailFragmentListener());
}
transaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
// Setting Properties after fragment is created
if (PhoneCapabilityTester.isUsingTwoPanesInFavorites(this)) {
mFavoritesFragment.enableQuickContact(true);
mFavoritesFragment.setDisplayType(DisplayType.STARRED_ONLY);
} else {
// For 2-pane in All and Groups but not in Favorites fragment, show the chevron
// for quick contact popup
mFavoritesFragment.enableQuickContact(isUsingTwoPanes);
mFavoritesFragment.setDisplayType(DisplayType.STREQUENT);
}
// Configure action bar
mActionBarAdapter = new ActionBarAdapter(this, this, getActionBar(), isUsingTwoPanes);
mActionBarAdapter.initialize(savedState, mRequest);
invalidateOptionsMenuIfNeeded();
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java b/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
index 72910fdf..c653e3c3 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
@@ -1,830 +1,836 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdfparser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.exceptions.WrappedIOException;
import org.apache.pdfbox.io.RandomAccess;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.fdf.FDFDocument;
import org.apache.pdfbox.persistence.util.COSObjectKey;
/**
* This class will handle the parsing of the PDF document.
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.53 $
*/
public class PDFParser extends BaseParser
{
/**
* Log instance.
*/
private static final Log log = LogFactory.getLog(PDFParser.class);
private static final int SPACE_BYTE = 32;
private static final String PDF_HEADER = "%PDF-";
private static final String FDF_HEADER = "%FDF-";
/**
* A list of duplicate objects found when Parsing the PDF
* File.
*/
private List conflictList = new ArrayList();
/**
* Temp file directory.
*/
private File tempDirectory = null;
private RandomAccess raf = null;
/**
* Constructor.
*
* @param input The input stream that contains the PDF document.
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser( InputStream input ) throws IOException {
this(input, null, FORCE_PARSING);
}
/**
* Constructor to allow control over RandomAccessFile.
* @param input The input stream that contains the PDF document.
* @param rafi The RandomAccessFile to be used in internal COSDocument
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser(InputStream input, RandomAccess rafi)
throws IOException {
this(input, rafi, FORCE_PARSING);
}
/**
* Constructor to allow control over RandomAccessFile.
* Also enables parser to skip corrupt objects to try and force parsing
* @param input The input stream that contains the PDF document.
* @param rafi The RandomAccessFile to be used in internal COSDocument
* @param force When true, the parser will skip corrupt pdf objects and
* will continue parsing at the next object in the file
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser(InputStream input, RandomAccess rafi, boolean force)
throws IOException {
super(input, force);
this.raf = rafi;
}
/**
* This is the directory where pdfbox will create a temporary file
* for storing pdf document stream in. By default this directory will
* be the value of the system property java.io.tmpdir.
*
* @param tmpDir The directory to create scratch files needed to store
* pdf document streams.
*/
public void setTempDirectory( File tmpDir )
{
tempDirectory = tmpDir;
}
/**
* Returns true if parsing should be continued. By default, forceParsing is returned.
* This can be overridden to add application specific handling (for example to stop
* parsing when the number of exceptions thrown exceed a certain number).
*
* @param e The exception if vailable. Can be null if there is no exception available
*/
protected boolean isContinueOnError(Exception e)
{
return forceParsing;
}
/**
* This will parse the stream and populate the COSDocument object. This will close
* the stream when it is done parsing.
*
* @throws IOException If there is an error reading from the stream or corrupt data
* is found.
*/
public void parse() throws IOException
{
try
{
if ( raf == null )
{
if( tempDirectory != null )
{
document = new COSDocument( tempDirectory );
}
else
{
document = new COSDocument();
}
}
else
{
document = new COSDocument( raf );
}
setDocument( document );
parseHeader();
//Some PDF files have garbage between the header and the
//first object
skipToNextObj();
boolean wasLastParsedObjectEOF = false;
try
{
while(true)
{
if(pdfSource.isEOF())
{
break;
}
try
{
wasLastParsedObjectEOF = parseObject();
}
catch(IOException e)
{
if(isContinueOnError(e))
{
/*
* Warning is sent to the PDFBox.log and to the Console that
* we skipped over an object
*/
log.warn("Parsing Error, Skipping Object", e);
skipToNextObj();
}
else
{
throw e;
}
}
skipSpaces();
}
//Test if we saw a trailer section. If not, look for an XRef Stream (Cross-Reference Stream)
//to populate the trailer and xref information. For PDF 1.5 and above
if( document.getTrailer() == null )
{
document.parseXrefStreams();
}
if( !document.isEncrypted() )
{
document.dereferenceObjectStreams();
}
ConflictObj.resolveConflicts(document, conflictList);
}
catch( IOException e )
{
/*
* PDF files may have random data after the EOF marker. Ignore errors if
* last object processed is EOF.
*/
if( !wasLastParsedObjectEOF )
{
throw e;
}
}
}
catch( Throwable t )
{
//so if the PDF is corrupt then close the document and clear
//all resources to it
if( document != null )
{
document.close();
}
if( t instanceof IOException )
{
throw (IOException)t;
}
else
{
throw new WrappedIOException( t );
}
}
finally
{
pdfSource.close();
}
}
/**
* Skip to the start of the next object. This is used to recover
* from a corrupt object. This should handle all cases that parseObject
* supports. This assumes that the next object will
* start on its own line.
*
* @throws IOException
*/
private void skipToNextObj() throws IOException
{
byte[] b = new byte[16];
Pattern p = Pattern.compile("\\d+\\s+\\d+\\s+obj.*", Pattern.DOTALL);
/* Read a buffer of data each time to see if it starts with a
* known keyword. This is not the most efficient design, but we should
* rarely be needing this function. We could update this to use the
* circular buffer, like in readUntilEndStream().
*/
while(!pdfSource.isEOF())
{
int l = pdfSource.read(b);
if(l < 1)
{
break;
}
String s = new String(b, "US-ASCII");
if(s.startsWith("trailer") ||
s.startsWith("xref") ||
s.startsWith("startxref") ||
s.startsWith("stream") ||
p.matcher(s).matches())
{
pdfSource.unread(b);
break;
}
else
{
pdfSource.unread(b, 1, l-1);
}
}
}
private void parseHeader() throws IOException
{
// read first line
String header = readLine();
// some pdf-documents are broken and the pdf-version is in one of the following lines
if ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
header = readLine();
while ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
// if a line starts with a digit, it has to be the first one with data in it
if ((header.length() > 0) && (Character.isDigit(header.charAt(0))))
{
break;
}
header = readLine();
}
}
// nothing found
if ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
throw new IOException( "Error: Header doesn't contain versioninfo" );
}
//sometimes there are some garbage bytes in the header before the header
//actually starts, so lets try to find the header first.
int headerStart = header.indexOf( PDF_HEADER );
if (headerStart == -1)
{
headerStart = header.indexOf(FDF_HEADER);
}
//greater than zero because if it is zero then
//there is no point of trimming
if ( headerStart > 0 )
{
//trim off any leading characters
header = header.substring( headerStart, header.length() );
}
/*
* This is used if there is garbage after the header on the same line
*/
if (header.startsWith(PDF_HEADER))
{
if(!header.matches(PDF_HEADER + "\\d.\\d"))
{
String headerGarbage = header.substring(PDF_HEADER.length()+3, header.length()) + "\n";
header = header.substring(0, PDF_HEADER.length()+3);
pdfSource.unread(headerGarbage.getBytes("ISO-8859-1"));
}
}
else
{
if(!header.matches(FDF_HEADER + "\\d.\\d"))
{
String headerGarbage = header.substring(FDF_HEADER.length()+3, header.length()) + "\n";
header = header.substring(0, FDF_HEADER.length()+3);
pdfSource.unread(headerGarbage.getBytes("ISO-8859-1"));
}
}
document.setHeaderString(header);
try
{
if (header.startsWith( PDF_HEADER ))
{
float pdfVersion = Float. parseFloat(
header.substring( PDF_HEADER.length(), Math.min( header.length(), PDF_HEADER .length()+3) ) );
document.setVersion( pdfVersion );
}
else
{
float pdfVersion = Float. parseFloat(
header.substring( FDF_HEADER.length(), Math.min( header.length(), FDF_HEADER.length()+3) ) );
document.setVersion( pdfVersion );
}
}
catch ( NumberFormatException e )
{
throw new IOException( "Error getting pdf version:" + e );
}
}
/**
* This will get the document that was parsed. parse() must be called before this is called.
* When you are done with this document you must call close() on it to release
* resources.
*
* @return The document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public COSDocument getDocument() throws IOException
{
if( document == null )
{
throw new IOException( "You must call parse() before calling getDocument()" );
}
return document;
}
/**
* This will get the PD document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public PDDocument getPDDocument() throws IOException
{
return new PDDocument( getDocument() );
}
/**
* This will get the FDF document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public FDFDocument getFDFDocument() throws IOException
{
return new FDFDocument( getDocument() );
}
/**
* This will parse the next object from the stream and add it to
* the local state.
*
* @return Returns true if the processed object had an endOfFile marker
*
* @throws IOException If an IO error occurs.
*/
private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
eof = readLine(); // if there's more data to read, get the EOF flag
- // verify that EOF exists
+ // verify that EOF exists (see PDFBOX-979 for documentation on special cases)
if(!"%%EOF".equals(eof)) {
- // PDF does not conform to spec, we should warn someone
- log.warn("expected='%%EOF' actual='" + eof + "'");
- // if we're not at the end of a file, just put it back and move on
- if(!pdfSource.isEOF()) {
- pdfSource.unread(eof.getBytes("ISO-8859-1"));
- pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
+ if(eof.startsWith("%%EOF")) {
+ // content after marker -> unread with first space byte for read newline
+ pdfSource.unread(SPACE_BYTE); // we read a whole line; add space as newline replacement
+ pdfSource.unread(eof.substring(5).getBytes("ISO-8859-1"));
+ } else {
+ // PDF does not conform to spec, we should warn someone
+ log.warn("expected='%%EOF' actual='" + eof + "'");
+ // if we're not at the end of a file, just put it back and move on
+ if(!pdfSource.isEOF()) {
+ pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
+ pdfSource.unread(eof.getBytes("ISO-8859-1"));
+ }
}
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( SPACE_BYTE ); // add a space first in place of the newline consumed by readline()
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
/**
* Adds a new ConflictObj to the conflictList.
* @param offset the offset of the ConflictObj
* @param key The COSObjectKey of this object
* @param pb The COSBase of this conflictObj
* @throws IOException
*/
private void addObjectToConflicts(int offset, COSObjectKey key, COSBase pb) throws IOException
{
COSObject obj = new COSObject(null);
obj.setObjectNumber( COSInteger.get( key.getNumber() ) );
obj.setGenerationNumber( COSInteger.get( key.getGeneration() ) );
obj.setObject(pb);
ConflictObj conflictObj = new ConflictObj(offset, key, obj);
conflictList.add(conflictObj);
}
/**
* This will parse the startxref section from the stream.
* The startxref value is ignored.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseStartXref() throws IOException
{
if(pdfSource.peek() != 's')
{
return false;
}
String startXRef = readString();
if( !startXRef.trim().equals( "startxref" ) )
{
return false;
}
skipSpaces();
/* This integer is the byte offset of the first object referenced by the xref or xref stream
* Not needed for PDFbox
*/
readInt();
return true;
}
/**
* This will parse the xref table from the stream and add it to the state
* The XrefTable contents are ignored.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseXrefTable() throws IOException
{
if(pdfSource.peek() != 'x')
{
return false;
}
String xref = readString();
if( !xref.trim().equals( "xref" ) )
{
return false;
}
/*
* Xref tables can have multiple sections.
* Each starts with a starting object id and a count.
*/
while(true)
{
int currObjID = readInt(); // first obj id
int count = readInt(); // the number of objects in the xref table
skipSpaces();
for(int i = 0; i < count; i++)
{
if(pdfSource.isEOF() || isEndOfName((char)pdfSource.peek()))
{
break;
}
if(pdfSource.peek() == 't')
{
break;
}
//Ignore table contents
String currentLine = readLine();
String[] splitString = currentLine.split(" ");
if (splitString.length < 3)
{
log.warn("invalid xref line: " + currentLine);
break;
}
/* This supports the corrupt table as reported in
* PDFBOX-474 (XXXX XXX XX n) */
if(splitString[splitString.length-1].equals("n"))
{
try
{
int currOffset = Integer.parseInt(splitString[0]);
int currGenID = Integer.parseInt(splitString[1]);
COSObjectKey objKey = new COSObjectKey(currObjID, currGenID);
document.setXRef(objKey, currOffset);
}
catch(NumberFormatException e)
{
throw new IOException(e.getMessage());
}
}
else if(!splitString[2].equals("f"))
{
throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID);
}
currObjID++;
skipSpaces();
}
skipSpaces();
char c = (char)pdfSource.peek();
if(c < '0' || c > '9')
{
break;
}
}
return true;
}
/**
* This will parse the trailer from the stream and add it to the state.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseTrailer() throws IOException
{
if(pdfSource.peek() != 't')
{
return false;
}
//read "trailer"
String nextLine = readLine();
if( !nextLine.trim().equals( "trailer" ) )
{
// in some cases the EOL is missing and the trailer immediately
// continues with "<<" or with a blank character
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
if (nextLine.startsWith("trailer"))
{
byte[] b = nextLine.getBytes("ISO-8859-1");
int len = "trailer".length();
pdfSource.unread('\n');
pdfSource.unread(b, len, b.length-len);
}
else
{
return false;
}
}
// in some cases the EOL is missing and the trailer continues with " <<"
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
skipSpaces();
COSDictionary parsedTrailer = parseCOSDictionary();
COSDictionary docTrailer = document.getTrailer();
if( docTrailer == null )
{
document.setTrailer( parsedTrailer );
}
else
{
docTrailer.addAll( parsedTrailer );
}
skipSpaces();
return true;
}
/**
* Used to resolve conflicts when a PDF Document has multiple objects with
* the same id number. Ideally, we could use the Xref table when parsing
* the document to be able to determine which of the objects with the same ID
* is correct, but we do not have access to the Xref Table during parsing.
* Instead, we queue up the conflicts and resolve them after the Xref has
* been parsed. The Objects listed in the Xref Table are kept and the
* others are ignored.
*/
private static class ConflictObj
{
private int offset;
private COSObjectKey objectKey;
private COSObject object;
public ConflictObj(int offsetValue, COSObjectKey key, COSObject pdfObject)
{
this.offset = offsetValue;
this.objectKey = key;
this.object = pdfObject;
}
public String toString()
{
return "Object(" + offset + ", " + objectKey + ")";
}
/**
* Sometimes pdf files have objects with the same ID number yet are
* not referenced by the Xref table and therefore should be excluded.
* This method goes through the conflicts list and replaces the object stored
* in the objects array with this one if it is referenced by the xref
* table.
* @throws IOException
*/
private static void resolveConflicts(COSDocument document, List conflictList) throws IOException
{
Iterator conflicts = conflictList.iterator();
while(conflicts.hasNext())
{
ConflictObj o = (ConflictObj)conflicts.next();
Integer offset = new Integer(o.offset);
if(document.getXrefTable().containsValue(offset))
{
COSObject pdfObject = document.getObjectFromPool(o.objectKey);
pdfObject.setObject(o.object.getObject());
}
}
}
}
}
| false | true |
private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
eof = readLine(); // if there's more data to read, get the EOF flag
// verify that EOF exists
if(!"%%EOF".equals(eof)) {
// PDF does not conform to spec, we should warn someone
log.warn("expected='%%EOF' actual='" + eof + "'");
// if we're not at the end of a file, just put it back and move on
if(!pdfSource.isEOF()) {
pdfSource.unread(eof.getBytes("ISO-8859-1"));
pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
}
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( SPACE_BYTE ); // add a space first in place of the newline consumed by readline()
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
|
private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
eof = readLine(); // if there's more data to read, get the EOF flag
// verify that EOF exists (see PDFBOX-979 for documentation on special cases)
if(!"%%EOF".equals(eof)) {
if(eof.startsWith("%%EOF")) {
// content after marker -> unread with first space byte for read newline
pdfSource.unread(SPACE_BYTE); // we read a whole line; add space as newline replacement
pdfSource.unread(eof.substring(5).getBytes("ISO-8859-1"));
} else {
// PDF does not conform to spec, we should warn someone
log.warn("expected='%%EOF' actual='" + eof + "'");
// if we're not at the end of a file, just put it back and move on
if(!pdfSource.isEOF()) {
pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
pdfSource.unread(eof.getBytes("ISO-8859-1"));
}
}
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( SPACE_BYTE ); // add a space first in place of the newline consumed by readline()
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
|
diff --git a/src/edu/ucla/cens/andwellness/prompt/remoteactivity/RemoteActivityPrompt.java b/src/edu/ucla/cens/andwellness/prompt/remoteactivity/RemoteActivityPrompt.java
index 3b65912..56de981 100644
--- a/src/edu/ucla/cens/andwellness/prompt/remoteactivity/RemoteActivityPrompt.java
+++ b/src/edu/ucla/cens/andwellness/prompt/remoteactivity/RemoteActivityPrompt.java
@@ -1,441 +1,441 @@
package edu.ucla.cens.andwellness.prompt.remoteactivity;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import edu.ucla.cens.andwellness.R;
import edu.ucla.cens.andwellness.prompt.AbstractPrompt;
import edu.ucla.cens.systemlog.Log;
/**
* Prompt that will launch a remote Activity that can either be part of this
* application or another application installed on the system. The remote
* Activity can be called as soon as this prompt loads by setting the
* 'autolaunch' field or later via a "Replay" button. The number of replays
* can also be set.
*
* @author John Jenkins
* @version 1.0
*/
public class RemoteActivityPrompt extends AbstractPrompt implements OnClickListener
{
private static final String TAG = "RemoteActivityPrompt";
private static final String FEEDBACK_STRING = "feedback";
private static final String SINGLE_VALUE_STRING = "score";
private String packageName;
private String activityName;
private String actionName;
private JSONArray responseArray;
private TextView feedbackText;
private Button launchButton;
private Activity callingActivity;
private boolean launched;
private boolean autolaunch;
private int retries;
/**
* Basic default constructor.
*/
public RemoteActivityPrompt()
{
super();
launched = false;
}
/**
* Creates the View from an XML file and sets up the local variables for
* the Views contained within. Then, if automatic launch is turned on it
* will attempt to automatically launch the remote Activity.
*/
@Override
public View getView(Context context)
{
try
{
callingActivity = (Activity) context;
}
catch(ClassCastException e)
{
callingActivity = null;
Log.e(TAG, "getView() recieved a Context that wasn't an Activity.");
// Should we error out here?
}
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.prompt_remote_activity, null);
feedbackText = (TextView) layout.findViewById(R.id.prompt_remote_activity_feedback);
launchButton = (Button) layout.findViewById(R.id.prompt_remote_activity_replay_button);
launchButton.setOnClickListener(this);
launchButton.setText((!launched && !autolaunch) ? "Launch" : "Relaunch");
if(retries > 0)
{
launchButton.setVisibility(View.VISIBLE);
}
else
{
if(!launched && !autolaunch)
{
launchButton.setVisibility(View.VISIBLE);
}
else
{
launchButton.setVisibility(View.GONE);
}
}
if(autolaunch && !launched)
{
launchActivity();
}
return layout;
}
/**
* If the 'resultCode' indicates failure then we treat it as if the user
* has skipped the prompt. If skipping is not allowed, we log it as an
* error, but we do not make an entry in the results array to prevent
* corrupting it nor do we set as skipped to prevent us from corrupting
* the entire survey.
*
* If the 'resultCode' indicates success then we check to see what was
* returned via the parameterized 'data' object. If 'data' is null, we put
* an empty JSONObject in the array to indicate that something went wrong.
* If 'data' is not null, we get all the key-value pairs from the data's
* extras and place them in a JSONObject. If the keys for these extras are
* certain "special" return codes, some of which are required, then we
* handle those as well which may or may not include putting them in the
* JSONObject. Finally, we put the JSONObject in the JSONArray that is the
* return value for this prompt type.
*/
@Override
public void handleActivityResult(Context context, int requestCode, int resultCode, Intent data)
{
if(resultCode == Activity.RESULT_CANCELED)
{
if(mSkippable.equalsIgnoreCase("true"))
{
this.setSkipped(true);
}
else if(mSkippable.equalsIgnoreCase("false"))
{
// The Activity was canceled for some reason, but it shouldn't
// have been.
Log.e(TAG, "The Activity was canceled, but the prompt isn't set as skippable.");
}
else
{
// This should _never_ happen!
Log.e(TAG, "Invalid 'skippable' value: " + mSkippable);
}
}
else if(resultCode == Activity.RESULT_OK)
{
if(data != null)
{
if(responseArray == null)
{
responseArray = new JSONArray();
}
boolean singleValueFound = false;
JSONObject currResponse = new JSONObject();
Bundle extras = data.getExtras();
Iterator<String> keysIter = extras.keySet().iterator();
while(keysIter.hasNext())
{
String nextKey = keysIter.next();
if(FEEDBACK_STRING.equals(nextKey))
{
feedbackText.setText(extras.getString(nextKey));
}
else
{
try
{
- currResponse.put(nextKey, extras.get(nextKey).toString());
+ currResponse.put(nextKey, extras.get(nextKey));
}
catch(JSONException e)
{
Log.e(TAG, "Invalid return value from remote Activity for key: " + nextKey);
}
if(SINGLE_VALUE_STRING.equals(nextKey))
{
singleValueFound = true;
}
}
}
if(singleValueFound)
{
responseArray.put(currResponse);
}
else
{
// We cannot add this to the list of responses because it
// will be rejected for not containing the single-value
// value.
Log.e(TAG, "The remote Activity is not returning a single value which is required for CSV export.");
}
}
else
{
// If the data is null, we put an empty JSONObject in the
// array to indicate that the data was null.
responseArray.put(new JSONObject());
Log.e(TAG, "The data returned by the remote Activity was null.");
}
}
// TODO: Possibly support user-defined Activity results:
// resultCode > Activity.RESULT_FIRST_USER
//
// One obvious possibility is some sort of "SKIPPED" return code.
}
/**
* Returns the JSONObject that it has created from the values Bundled in
* the return of the remote Activity.
*/
@Override
protected Object getTypeSpecificResponseObject()
{
return responseArray;
}
/**
* There are no extras for this object.
*/
@Override
protected Object getTypeSpecificExtrasObject()
{
return null;
}
/**
* Clears the local variable by recreating and reinstantiating it to a new
* one.
*/
@Override
protected void clearTypeSpecificResponseData()
{
responseArray = new JSONArray();
}
/**
* Called when the "Replay" button is clicked. If autolaunch is not on and
* the remote Activity hasn't been launched yet, it will switch the text
* back to "Replay" from "Play" and launch the Activity. If there weren't
* any replays allowed, it will also remove the "Replay" button.
*
* If the remote Activity has been launched be it from this button or from
* the autolaunch, it will check the number of retries left. If it is out
* of retries then it is an error to be in this state, but it will simply
* hide the button and leave the function. If there are retries left, it
* will decrement the number left, check if the user is out of replays in
* which case it will hide the "Replay" button, and will launch the remote
* Activity.
*/
@Override
public void onClick(View v)
{
if(launched)
{
if(retries > 0)
{
retries--;
if(retries <= 0)
{
launchButton.setVisibility(View.GONE);
}
launchActivity();
}
else
{
launchButton.setVisibility(View.GONE);
}
}
else if(!autolaunch)
{
launchButton.setText("Relaunch");
if(retries <= 0)
{
launchButton.setVisibility(View.GONE);
}
launchActivity();
}
else
{
Log.e(TAG, "Autolaunch is turned on, but I received a click on the \"Replay\" button before ever launching the remote Activity.");
}
}
/**
* Sets the name of the Package to which the remote Activity belongs.
*
* @param packageName The name of the Package to which the remote Activity
* belongs.
*
* @throws IllegalArgumentException Thrown if the 'packageName' is null or
* an empty string.
*
* @see {@link #setActivity(String)}
* @see {@link #setAction(String)}
*/
public void setPackage(String packageName) throws IllegalArgumentException
{
if((packageName == null) || packageName.equals(""))
{
throw new IllegalArgumentException("Invalid Package name.");
}
this.packageName = packageName;
}
/**
* Sets the Activity to be called within the remote Package.
*
* @param activityName The name of the Activity to be called within the
* remote Package.
*
* @throws IllegalArgumentException Thrown if 'activityName' is null or an
* empty string.
*
* @see {@link #setPackage(String)}
* @see {@link #setAction(String)}
*/
public void setActivity(String activityName) throws IllegalArgumentException
{
if((activityName == null) || packageName.equals(""))
{
throw new IllegalArgumentException("Invalid Activity name.");
}
this.activityName = activityName;
}
/**
* Sets the name of the Action as it is defined in the intent-filter of
* its Activity definition in the Manifest of its remote application.
*
* @param activityName The String representing the Action to be set in the
* Intent to the remote Activity.
*
* @throws IllegalArgumentException Thrown if 'actionName' is "null" or
* an empty string.
*
* @see {@link #setPackage(String)}
* @see {@link #setActivity(String)}
*/
public void setAction(String actionName) throws IllegalArgumentException
{
if((actionName == null) || (actionName.equals("")))
{
throw new IllegalArgumentException("Invalid Action name.");
}
this.actionName = actionName;
}
/**
* Sets the number of times that a user can relaunch the remote Activity.
*
* @param numRetries The number of times a user can relaunch the remote
* Activity.
*/
public void setRetries(int numRetries)
{
retries = numRetries;
}
/**
* Returns the number of remaining retries.
*
* @return The number of times the remote Activity can be relaunched via
* the "Replay" button, not counting the first replay if
* 'autolaunch' is off.
*/
public int getNumRetriesRemaining()
{
return retries;
}
/**
* Sets whether or not the Activity will launch automatically when the
* prompt is displayed. If it is not set to automatically launch then the
* "Replay" button will be shown and have its text set to "Play". On
* subsequent displays of this Activity, the button will have its text
* switched back to "Replay".
*
* @param autolaunch Whether or not the remote Activity should be launched
* automatically when this view loads.
*/
public void setAutolaunch(boolean autolaunch)
{
this.autolaunch = autolaunch;
}
/**
* Returns whether or not the remote Activity has ever been launched from
* this prompt. This includes both the 'autolaunch' and the "Replay"
* button.
*
* @return Whether or not the remote Activity has ever been launched from
* this prompt.
*/
public boolean hasLaunchedRemoteActivity()
{
return launched;
}
/**
* Creates an Intent from the given 'activityName' and then launches the
* Intent.
*/
private void launchActivity()
{
if(callingActivity != null)
{
Intent activityToLaunch = new Intent(actionName);
activityToLaunch.setComponent(new ComponentName(packageName, activityName));
Activity activityContext = (Activity) callingActivity;
try {
activityContext.startActivityForResult(activityToLaunch, 0);
launched = true;
} catch (ActivityNotFoundException e) {
Toast.makeText(callingActivity, "Required component is not installed", Toast.LENGTH_SHORT).show();
}
}
else
{
Log.e(TAG, "The calling Activity was null.");
}
}
}
| true | true |
public void handleActivityResult(Context context, int requestCode, int resultCode, Intent data)
{
if(resultCode == Activity.RESULT_CANCELED)
{
if(mSkippable.equalsIgnoreCase("true"))
{
this.setSkipped(true);
}
else if(mSkippable.equalsIgnoreCase("false"))
{
// The Activity was canceled for some reason, but it shouldn't
// have been.
Log.e(TAG, "The Activity was canceled, but the prompt isn't set as skippable.");
}
else
{
// This should _never_ happen!
Log.e(TAG, "Invalid 'skippable' value: " + mSkippable);
}
}
else if(resultCode == Activity.RESULT_OK)
{
if(data != null)
{
if(responseArray == null)
{
responseArray = new JSONArray();
}
boolean singleValueFound = false;
JSONObject currResponse = new JSONObject();
Bundle extras = data.getExtras();
Iterator<String> keysIter = extras.keySet().iterator();
while(keysIter.hasNext())
{
String nextKey = keysIter.next();
if(FEEDBACK_STRING.equals(nextKey))
{
feedbackText.setText(extras.getString(nextKey));
}
else
{
try
{
currResponse.put(nextKey, extras.get(nextKey).toString());
}
catch(JSONException e)
{
Log.e(TAG, "Invalid return value from remote Activity for key: " + nextKey);
}
if(SINGLE_VALUE_STRING.equals(nextKey))
{
singleValueFound = true;
}
}
}
if(singleValueFound)
{
responseArray.put(currResponse);
}
else
{
// We cannot add this to the list of responses because it
// will be rejected for not containing the single-value
// value.
Log.e(TAG, "The remote Activity is not returning a single value which is required for CSV export.");
}
}
else
{
// If the data is null, we put an empty JSONObject in the
// array to indicate that the data was null.
responseArray.put(new JSONObject());
Log.e(TAG, "The data returned by the remote Activity was null.");
}
}
// TODO: Possibly support user-defined Activity results:
// resultCode > Activity.RESULT_FIRST_USER
//
// One obvious possibility is some sort of "SKIPPED" return code.
}
|
public void handleActivityResult(Context context, int requestCode, int resultCode, Intent data)
{
if(resultCode == Activity.RESULT_CANCELED)
{
if(mSkippable.equalsIgnoreCase("true"))
{
this.setSkipped(true);
}
else if(mSkippable.equalsIgnoreCase("false"))
{
// The Activity was canceled for some reason, but it shouldn't
// have been.
Log.e(TAG, "The Activity was canceled, but the prompt isn't set as skippable.");
}
else
{
// This should _never_ happen!
Log.e(TAG, "Invalid 'skippable' value: " + mSkippable);
}
}
else if(resultCode == Activity.RESULT_OK)
{
if(data != null)
{
if(responseArray == null)
{
responseArray = new JSONArray();
}
boolean singleValueFound = false;
JSONObject currResponse = new JSONObject();
Bundle extras = data.getExtras();
Iterator<String> keysIter = extras.keySet().iterator();
while(keysIter.hasNext())
{
String nextKey = keysIter.next();
if(FEEDBACK_STRING.equals(nextKey))
{
feedbackText.setText(extras.getString(nextKey));
}
else
{
try
{
currResponse.put(nextKey, extras.get(nextKey));
}
catch(JSONException e)
{
Log.e(TAG, "Invalid return value from remote Activity for key: " + nextKey);
}
if(SINGLE_VALUE_STRING.equals(nextKey))
{
singleValueFound = true;
}
}
}
if(singleValueFound)
{
responseArray.put(currResponse);
}
else
{
// We cannot add this to the list of responses because it
// will be rejected for not containing the single-value
// value.
Log.e(TAG, "The remote Activity is not returning a single value which is required for CSV export.");
}
}
else
{
// If the data is null, we put an empty JSONObject in the
// array to indicate that the data was null.
responseArray.put(new JSONObject());
Log.e(TAG, "The data returned by the remote Activity was null.");
}
}
// TODO: Possibly support user-defined Activity results:
// resultCode > Activity.RESULT_FIRST_USER
//
// One obvious possibility is some sort of "SKIPPED" return code.
}
|
diff --git a/solr/src/java/org/apache/solr/response/BaseResponseWriter.java b/solr/src/java/org/apache/solr/response/BaseResponseWriter.java
index 2d80526bf..b63604813 100644
--- a/solr/src/java/org/apache/solr/response/BaseResponseWriter.java
+++ b/solr/src/java/org/apache/solr/response/BaseResponseWriter.java
@@ -1,331 +1,330 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.response;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.DocList;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.DocIterator;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
/**
*
*
* This class serves as a basis from which {@link QueryResponseWriter}s can be
* developed. The class provides a single method
* {@link #write(SingleResponseWriter, SolrQueryRequest, SolrQueryResponse)}
* that allows users to implement a {@link SingleResponseWriter} sub-class which
* defines how to output {@link SolrInputDocument}s or a
* {@link SolrDocumentList}.
*
* @version $Id$
* @since 1.5
*
*/
public abstract class BaseResponseWriter {
private static final Logger LOG = LoggerFactory
.getLogger(BaseResponseWriter.class);
private static final String SCORE_FIELD = "score";
/**
*
* The main method that allows users to write {@link SingleResponseWriter}s
* and provide them as the initial parameter <code>responseWriter</code> to
* this method which defines how output should be generated.
*
* @param responseWriter
* The user-provided {@link SingleResponseWriter} implementation.
* @param request
* The provided {@link SolrQueryRequest}.
* @param response
* The provided {@link SolrQueryResponse}.
* @throws IOException
* If any error occurs.
*/
public void write(SingleResponseWriter responseWriter,
SolrQueryRequest request, SolrQueryResponse response) throws IOException {
responseWriter.start();
NamedList nl = response.getValues();
for (int i = 0; i < nl.size(); i++) {
String name = nl.getName(i);
Object val = nl.getVal(i);
if ("responseHeader".equals(name)) {
Boolean omitHeader = request.getParams().getBool(CommonParams.OMIT_HEADER);
if (omitHeader == null || !omitHeader) responseWriter.writeResponseHeader((NamedList) val);
} else if (val instanceof SolrDocumentList) {
SolrDocumentList list = (SolrDocumentList) val;
DocListInfo info = new DocListInfo((int)list.getNumFound(), list.size(), (int)list.getStart(), list.getMaxScore());
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (SolrDocument solrDocument : list)
responseWriter.writeDoc(solrDocument);
responseWriter.endDocumentList();
} else {
responseWriter.writeAllDocs(info, list);
}
} else if (val instanceof DocList) {
DocList docList = (DocList) val;
int sz = docList.size();
IdxInfo idxInfo = new IdxInfo(request.getSchema(), request
.getSearcher(), response.getReturnFields());
DocListInfo info = new DocListInfo(docList.matches(), docList.size(),docList.offset(),
docList.maxScore());
DocIterator iterator = docList.iterator();
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
responseWriter.writeDoc(sdoc);
}
- responseWriter.end();
} else {
ArrayList<SolrDocument> list = new ArrayList<SolrDocument>(docList
.size());
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
list.add(sdoc);
}
responseWriter.writeAllDocs(info, list);
}
} else {
responseWriter.writeOther(name, val);
}
}
responseWriter.end();
}
/**No ops implementation so that the implementing classes do not have to do it
*/
public void init(NamedList args){}
private static class IdxInfo {
IndexSchema schema;
SolrIndexSearcher searcher;
Set<String> returnFields;
boolean includeScore;
private IdxInfo(IndexSchema schema, SolrIndexSearcher searcher,
Set<String> returnFields) {
this.schema = schema;
this.searcher = searcher;
this.includeScore = returnFields != null
&& returnFields.contains(SCORE_FIELD);
if (returnFields != null) {
if (returnFields.size() == 0 || (returnFields.size() == 1 && includeScore) || returnFields.contains("*")) {
returnFields = null; // null means return all stored fields
}
}
this.returnFields = returnFields;
}
}
private static SolrDocument getDoc(int id, IdxInfo info) throws IOException {
Document doc = info.searcher.doc(id);
SolrDocument solrDoc = new SolrDocument();
for (Fieldable f : doc.getFields()) {
String fieldName = f.name();
if (info.returnFields != null && !info.returnFields.contains(fieldName))
continue;
SchemaField sf = info.schema.getFieldOrNull(fieldName);
FieldType ft = null;
if (sf != null) ft = sf.getType();
Object val = null;
if (ft == null) { // handle fields not in the schema
if (f.isBinary())
val = f.getBinaryValue();
else
val = f.stringValue();
} else {
try {
if (BinaryResponseWriter.KNOWN_TYPES.contains(ft.getClass())) {
val = ft.toObject(f);
} else {
val = ft.toExternal(f);
}
} catch (Exception e) {
// There is a chance of the underlying field not really matching the
// actual field type . So ,it can throw exception
LOG.warn("Error reading a field from document : " + solrDoc, e);
// if it happens log it and continue
continue;
}
}
if (sf != null && sf.multiValued() && !solrDoc.containsKey(fieldName)) {
ArrayList l = new ArrayList();
l.add(val);
solrDoc.addField(fieldName, l);
} else {
solrDoc.addField(fieldName, val);
}
}
return solrDoc;
}
public static class DocListInfo {
public final int numFound;
public final int start ;
public Float maxScore = null;
public final int size;
public DocListInfo(int numFound, int sz,int start, Float maxScore) {
this.numFound = numFound;
size = sz;
this.start = start;
this.maxScore = maxScore;
}
}
/**
*
* Users wanting to define custom {@link QueryResponseWriter}s that deal with
* {@link SolrInputDocument}s and {@link SolrDocumentList} should override the
* methods for this class. All the methods are w/o body because the user is left
* to choose which all methods are required for his purpose
*/
public static abstract class SingleResponseWriter {
/**
* This method is called at the start of the {@link QueryResponseWriter}
* output. Override this method if you want to provide a header for your
* output, e.g., XML headers, etc.
*
* @throws IOException
* if any error occurs.
*/
public void start() throws IOException { }
/**
* This method is called at the start of processing a
* {@link SolrDocumentList}. Those that override this method are provided
* with {@link DocListInfo} object to use to inspect the output
* {@link SolrDocumentList}.
*
* @param info Information about the {@link SolrDocumentList} to output.
*/
public void startDocumentList(String name, DocListInfo info) throws IOException { }
/**
* This method writes out a {@link SolrDocument}, on a doc-by-doc basis.
* This method is only called when {@link #isStreamingDocs()} returns true.
*
* @param solrDocument
* The doc-by-doc {@link SolrDocument} to transform into output as
* part of this {@link QueryResponseWriter}.
*/
public void writeDoc(SolrDocument solrDocument) throws IOException { }
/**
* This method is called at the end of outputting a {@link SolrDocumentList}
* or on a doc-by-doc {@link SolrDocument} basis.
*/
public void endDocumentList() throws IOException { }
/**
* This method defines how to output the {@link SolrQueryResponse} header
* which is provided as a {@link NamedList} parameter.
*
* @param responseHeader
* The response header to output.
*/
public void writeResponseHeader(NamedList responseHeader) throws IOException { }
/**
* This method is called at the end of the {@link QueryResponseWriter}
* lifecycle. Implement this method to add a footer to your output, e.g., in
* the case of XML, the outer tag for your tag set, etc.
*
* @throws IOException
* If any error occurs.
*/
public void end() throws IOException { }
/**
* Define this method to control how output is written by this
* {@link QueryResponseWriter} if the output is not a
* {@link SolrInputDocument} or a {@link SolrDocumentList}.
*
* @param name
* The name of the object to output.
* @param other
* The object to output.
* @throws IOException
* If any error occurs.
*/
public void writeOther(String name, Object other) throws IOException { }
/**
* Overriding this method to return false forces all
* {@link SolrInputDocument}s to be spit out as a {@link SolrDocumentList}
* so they can be processed as a whole, rather than on a doc-by-doc basis.
* If set to false, this method calls
* {@link #writeAllDocs(DocListInfo, List)}, else if set to true, then this
* method forces calling {@link #writeDoc(SolrDocument)} on a doc-by-doc
* basis. one
*
* @return True to force {@link #writeDoc(SolrDocument)} to be called, False
* to force {@link #writeAllDocs(DocListInfo, List)} to be called.
*/
public boolean isStreamingDocs() { return true; }
/**
* Writes out all {@link SolrInputDocument}s . This is invoked only if
* {@link #isStreamingDocs()} returns false.
*
* @param info
* Information about the {@link List} of {@link SolrDocument}s to
* output.
* @param allDocs
* A {@link List} of {@link SolrDocument}s to output.
* @throws IOException
* If any error occurs.
*/
public void writeAllDocs(DocListInfo info, List<SolrDocument> allDocs) throws IOException { }
}
}
| true | true |
public void write(SingleResponseWriter responseWriter,
SolrQueryRequest request, SolrQueryResponse response) throws IOException {
responseWriter.start();
NamedList nl = response.getValues();
for (int i = 0; i < nl.size(); i++) {
String name = nl.getName(i);
Object val = nl.getVal(i);
if ("responseHeader".equals(name)) {
Boolean omitHeader = request.getParams().getBool(CommonParams.OMIT_HEADER);
if (omitHeader == null || !omitHeader) responseWriter.writeResponseHeader((NamedList) val);
} else if (val instanceof SolrDocumentList) {
SolrDocumentList list = (SolrDocumentList) val;
DocListInfo info = new DocListInfo((int)list.getNumFound(), list.size(), (int)list.getStart(), list.getMaxScore());
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (SolrDocument solrDocument : list)
responseWriter.writeDoc(solrDocument);
responseWriter.endDocumentList();
} else {
responseWriter.writeAllDocs(info, list);
}
} else if (val instanceof DocList) {
DocList docList = (DocList) val;
int sz = docList.size();
IdxInfo idxInfo = new IdxInfo(request.getSchema(), request
.getSearcher(), response.getReturnFields());
DocListInfo info = new DocListInfo(docList.matches(), docList.size(),docList.offset(),
docList.maxScore());
DocIterator iterator = docList.iterator();
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
responseWriter.writeDoc(sdoc);
}
responseWriter.end();
} else {
ArrayList<SolrDocument> list = new ArrayList<SolrDocument>(docList
.size());
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
list.add(sdoc);
}
responseWriter.writeAllDocs(info, list);
}
} else {
responseWriter.writeOther(name, val);
}
}
responseWriter.end();
}
|
public void write(SingleResponseWriter responseWriter,
SolrQueryRequest request, SolrQueryResponse response) throws IOException {
responseWriter.start();
NamedList nl = response.getValues();
for (int i = 0; i < nl.size(); i++) {
String name = nl.getName(i);
Object val = nl.getVal(i);
if ("responseHeader".equals(name)) {
Boolean omitHeader = request.getParams().getBool(CommonParams.OMIT_HEADER);
if (omitHeader == null || !omitHeader) responseWriter.writeResponseHeader((NamedList) val);
} else if (val instanceof SolrDocumentList) {
SolrDocumentList list = (SolrDocumentList) val;
DocListInfo info = new DocListInfo((int)list.getNumFound(), list.size(), (int)list.getStart(), list.getMaxScore());
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (SolrDocument solrDocument : list)
responseWriter.writeDoc(solrDocument);
responseWriter.endDocumentList();
} else {
responseWriter.writeAllDocs(info, list);
}
} else if (val instanceof DocList) {
DocList docList = (DocList) val;
int sz = docList.size();
IdxInfo idxInfo = new IdxInfo(request.getSchema(), request
.getSearcher(), response.getReturnFields());
DocListInfo info = new DocListInfo(docList.matches(), docList.size(),docList.offset(),
docList.maxScore());
DocIterator iterator = docList.iterator();
if (responseWriter.isStreamingDocs()) {
responseWriter.startDocumentList(name,info);
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
responseWriter.writeDoc(sdoc);
}
} else {
ArrayList<SolrDocument> list = new ArrayList<SolrDocument>(docList
.size());
for (int j = 0; j < sz; j++) {
SolrDocument sdoc = getDoc(iterator.nextDoc(), idxInfo);
if (idxInfo.includeScore && docList.hasScores()) {
sdoc.addField(SCORE_FIELD, iterator.score());
}
list.add(sdoc);
}
responseWriter.writeAllDocs(info, list);
}
} else {
responseWriter.writeOther(name, val);
}
}
responseWriter.end();
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyWikiModel.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyWikiModel.java
index 6bbf9aa3..c1dafab5 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyWikiModel.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyWikiModel.java
@@ -1,362 +1,367 @@
/**
* Copyright 2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.bliki;
import info.bliki.htmlcleaner.TagNode;
import info.bliki.wiki.filter.Util;
import info.bliki.wiki.model.Configuration;
import info.bliki.wiki.model.WikiModel;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import de.zib.scalaris.Connection;
import de.zib.scalaris.examples.wikipedia.RevisionResult;
import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler;
/**
* Wiki model using Scalaris to fetch (new) data, e.g. templates.
*
* @author Nico Kruber, [email protected]
*/
public class MyWikiModel extends WikiModel {
protected Connection connection;
protected Map<String, String> magicWordCache = new HashMap<String, String>();
private String fExternalWikiBaseFullURL;
private static final Configuration configuration = new Configuration();
static {
// BEWARE: fields in Configuration are static -> this changes all configurations!
configuration.addTemplateFunction("fullurl", MyFullurl.CONST);
configuration.addTemplateFunction("localurl", MyLocalurl.CONST);
// do not use interwiki links (some may be internal - bliki however favours interwiki links)
configuration.getInterwikiMap().clear();
// allow style attributes:
TagNode.addAllowedAttribute("style");
}
/**
* Creates a new wiki model to render wiki text using the given connection
* to Scalaris.
*
* @param imageBaseURL
* base url pointing to images - can contain ${image} for
* replacement
* @param linkBaseURL
* base url pointing to links - can contain ${title} for
* replacement
* @param connection
* connection to Scalaris
* @param namespace
* namespace of the wiki
*/
public MyWikiModel(String imageBaseURL, String linkBaseURL, Connection connection, MyNamespace namespace) {
super(configuration, null, namespace, imageBaseURL, linkBaseURL);
this.connection = connection;
this.fExternalWikiBaseFullURL = linkBaseURL;
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.AbstractWikiModel#getRawWikiContent(java.lang.String, java.lang.String, java.util.Map)
*/
@Override
public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
+ // (ugly) fix for template parameter replacement if no parameters given,
+ // e.g. "{{noun}}" in the simple English Wiktionary
+ if (templateParameters.isEmpty()) {
+ templateParameters.put("", null);
+ }
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
/**
* Fixes noinclude tags inside includeonly/onlyinclude not being filtered
* out by the template parsing.
*
* @param text
* the template's text
*
* @return the text without anything within noinclude tags
*/
private final String removeNoIncludeContents(String text) {
// do not alter if showing the template page:
if (getRecursionLevel() == 0) {
return text;
}
StringBuilder sb = new StringBuilder(text.length());
int curPos = 0;
while(true) {
// starting tag:
String startString = "<", endString = "noinclude>";
int index = Util.indexOfIgnoreCase(text, startString, endString, curPos);
if (index != (-1)) {
sb.append(text.substring(curPos, index));
curPos = index;
} else {
sb.append(text.substring(curPos));
return sb.toString();
}
// ending tag:
startString = "</"; endString = "noinclude>";
index = Util.indexOfIgnoreCase(text, startString, endString, curPos);
if (index != (-1)) {
curPos = index + startString.length() + endString.length();
} else {
return sb.toString();
}
}
}
/**
* Gets the contents of the newest revision of the page redirected to.
*
* @param pageName
* the name of the page redirected to
*
* @return the contents of the newest revision of that page or a placeholder
* string
*/
public String getRedirectContent(String pageName) {
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
// make PAGENAME in the redirected content work as expected
setPageName(pageName);
return getRevResult.revision.getText();
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: redirect to " + getRedirectLink() + " failed: " + getRevResult.message + "</b>";
return "#redirect [[" + pageName + "]]";
}
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.AbstractWikiModel#encodeTitleToUrl(java.lang.String, boolean)
*/
@Override
public String encodeTitleToUrl(String wikiTitle,
boolean firstCharacterAsUpperCase) {
try {
// some links may contain '_' which needs to be translated back to ' ':
wikiTitle = wikiTitle.replace('_', ' ');
return URLEncoder.encode(wikiTitle, "UTF-8");
} catch (UnsupportedEncodingException e) {
return super.encodeTitleToUrl(wikiTitle, firstCharacterAsUpperCase);
}
}
/**
* Gets the base URL for images (can contain ${image} for replacement).
*
* @return the base url for images
*/
public String getImageBaseURL() {
return fExternalImageBaseURL;
}
/**
* Gets the base URL for links (can contain ${title} for replacement).
*
* @return the base url for links
*/
public String getLinkBaseURL() {
return fExternalWikiBaseURL;
}
/**
* Gets the base URL for full links including "http://" (can contain ${title}
* for replacement).
*
* @return the base url for links
*/
public String getLinkBaseFullURL() {
return fExternalWikiBaseFullURL;
}
/**
* Sets the base URL for full links including "http://" (can contain ${title}
* for replacement).
*
* @param linkBaseFullURL
* the full link URL to set
*/
public void setLinkBaseFullURL(String linkBaseFullURL) {
this.fExternalWikiBaseFullURL = linkBaseFullURL;
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.WikiModel#getNamespace()
*/
@Override
public MyNamespace getNamespace() {
return (MyNamespace) super.getNamespace();
}
/**
* Formats the given number using the wiki's locale.
*
* Note: Currently, the English locale is always used.
*
* @param rawNumber
* whether the raw number should be returned
* @param number
* the number
*
* @return the formatted number
*/
public String formatStatisticNumber(boolean rawNumber, Number number) {
if (rawNumber) {
return number.toString();
} else {
// TODO: use locale from Wiki
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setGroupingUsed(true);
return nf.format(number);
}
}
/**
* Splits the given full title into its namespace and page title components.
*
* @param fullTitle
* the (full) title including a namespace (if present)
*
* @return a 2-element array with the namespace (index 0) and the page title
* (index 1)
*/
public static String[] splitNsTitle(String fullTitle) {
int colonIndex = fullTitle.indexOf(':');
if (colonIndex != (-1)) {
return new String[] { fullTitle.substring(0, colonIndex),
fullTitle.substring(colonIndex + 1) };
}
return new String[] {"", fullTitle};
}
/**
* Returns the namespace of a given page title.
*
* @param title
* the (full) title including a namespace (if present)
*
* @return the namespace part of the title or an empty string if no
* namespace
*
* @see #getTitleName(String)
* @see #splitNsTitle(String)
*/
public static String getNamespace(String title) {
return splitNsTitle(title)[0];
}
/**
* Returns the name of a given page title without its namespace.
*
* @param title
* the (full) title including a namespace (if present)
*
* @return the title part of the page title
*
* @see #getNamespace(String)
* @see #splitNsTitle(String)
*/
public static String getTitleName(String title) {
return splitNsTitle(title)[1];
}
/**
* Splits the given full title into its namespace, base and sub page
* components.
*
* @param fullTitle
* the (full) title including a namespace (if present)
*
* @return a 3-element array with the namespace (index 0), the base page
* (index 1) and the sub page (index 2)
*/
public static String[] splitNsBaseSubPage(String fullTitle) {
String[] split1 = splitNsTitle(fullTitle);
String namespace = split1[0];
String title = split1[1];
int colonIndex = title.lastIndexOf('/');
if (colonIndex != (-1)) {
return new String[] { namespace, title.substring(0, colonIndex),
title.substring(colonIndex + 1) };
}
return new String[] {namespace, title, ""};
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.AbstractWikiModel#appendRedirectLink(java.lang.String)
*/
@Override
public boolean appendRedirectLink(String redirectLink) {
// do not add redirection if we are parsing a template:
if (getRecursionLevel() == 0) {
return super.appendRedirectLink(redirectLink);
}
return true;
}
}
| true | true |
public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
|
public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
if (templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
|
diff --git a/src/main/java/thesmith/eventhorizon/controller/IndexController.java b/src/main/java/thesmith/eventhorizon/controller/IndexController.java
index b9ec7cc..6b183c4 100644
--- a/src/main/java/thesmith/eventhorizon/controller/IndexController.java
+++ b/src/main/java/thesmith/eventhorizon/controller/IndexController.java
@@ -1,243 +1,244 @@
package thesmith.eventhorizon.controller;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 thesmith.eventhorizon.model.Account;
import thesmith.eventhorizon.model.Snapshot;
import thesmith.eventhorizon.model.Status;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.google.appengine.repackaged.com.google.common.collect.Maps;
import com.google.appengine.repackaged.com.google.common.collect.Sets;
@Controller
public class IndexController extends BaseController {
public static final String FROM = "from";
private static final DateFormat format = new SimpleDateFormat("yyyy/MM/dd kk:mm:ss");
private static final DateFormat urlFormat = new SimpleDateFormat("yyyy/MM/dd/kk/mm/ss");
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}", method = RequestMethod.GET)
public String index(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, ModelMap model, HttpServletRequest request) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
this.setModel(personId, from, model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
this.setViewer(request, model);
return "index/index";
}
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}/{domain}/previous", method = RequestMethod.GET)
public String previous(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, @PathVariable("domain") String domain) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
Account account = accountService.account(personId, domain);
Status status = statusService.previous(account, from);
if (null == status)
status = statusService.find(account, from);
return String.format("redirect:/%s/%s/", personId, urlFormat.format(status.getCreated()));
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}/{domain}/next", method = RequestMethod.GET)
public String next(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, @PathVariable("domain") String domain) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
Account account = accountService.account(personId, domain);
Status status = statusService.next(account, from);
if (null == status)
status = statusService.find(account, from);
return String.format("redirect:/%s/%s/", personId, urlFormat.format(status.getCreated()));
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
@RequestMapping(value = "/{personId}/{domain}/previous", method = RequestMethod.GET)
public String previous(@PathVariable("personId") String personId, @PathVariable("domain") String domain,
@RequestParam("from") String from, ModelMap model) {
try {
Account account = accountService.account(personId, domain);
Status status = statusService.previous(account, this.parseDate(from));
if (null != status)
this.setModel(personId, status.getCreated(), model);
else
this.setModel(personId, this.parseDate(from), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
return "index/index";
}
@RequestMapping(value = "/{personId}/{domain}/next", method = RequestMethod.GET)
public String next(@PathVariable("personId") String personId, @PathVariable("domain") String domain,
@RequestParam("from") String from, ModelMap model) {
try {
Account account = accountService.account(personId, domain);
Status status = statusService.next(account, this.parseDate(from));
if (null != status)
this.setModel(personId, status.getCreated(), model);
else
this.setModel(personId, this.parseDate(from), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
return "index/index";
}
@RequestMapping(value = "/{personId}/now", method = RequestMethod.GET)
public String now(@PathVariable("personId") String personId, @RequestParam("from") String from, ModelMap model,
HttpServletRequest request) {
if (null != from && from.length() > 0) {
try {
this.setModel(personId, this.parseDate(from), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
this.setViewer(request, model);
return "index/index";
}
@RequestMapping(value = "/{personId}", method = RequestMethod.GET)
public String start(@PathVariable("personId") String personId, ModelMap model, HttpServletRequest request) {
this.setModel(personId, null, model);
this.setViewer(request, model);
return "index/index";
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String startNoPath(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
try {
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
if (null != host && host.contains(HOST_POSTFIX)) {
String personId = host.replace(HOST_POSTFIX, "");
if (!"www".equals(personId)) {
this.setModel(personId, null, model);
this.setViewer(request, model);
return "index/index";
}
}
} catch (MalformedURLException e) {
if (logger.isInfoEnabled())
logger.info("Unable to decode url from " + request.getRequestURL().toString());
}
+ model.addAttribute("secureHost", secureHost());
String view = redirectIndex(request);
if (null == view)
view = "index/home";
return view;
}
@RequestMapping(value = "/error", method = RequestMethod.GET)
public String error() {
return "error";
}
private void setModel(String personId, Date from, ModelMap model) {
List<Status> statuses = Lists.newArrayList();
Map<String, Account> accounts = accountMap(accountService.list(personId));
if (null != from) {
Snapshot snapshot = snapshotService.find(personId, from);
if (snapshot != null)
statuses = statusService.list(snapshot.getStatusIds(), from, accounts);
} else {
from = new Date();
for (Account account : accounts.values()) {
statuses.add(defaultStatus(personId, account.getDomain(), from));
}
model.addAttribute("refresh", true);
}
Set<String> emptyDomains = emptyDomains(accounts.keySet(), statuses);
model.addAttribute("statuses", statuses);
model.addAttribute("emptyDomains", emptyDomains);
model.addAttribute("personId", personId);
model.addAttribute("gravatar", userService.getGravatar(personId));
model.addAttribute("from", from);
model.addAttribute("secureHost", secureHost());
}
private Set<String> emptyDomains(Set<String> domains, List<Status> statuses) {
Set<String> foundDomains = Sets.newHashSet();
for (Status status : statuses) {
foundDomains.add(status.getDomain());
}
return Sets.difference(domains, foundDomains);
}
private Map<String, Account> accountMap(List<Account> accounts) {
Map<String, Account> accountMap = Maps.newHashMap();
for (Account account : accounts) {
accountMap.put(account.getDomain(), account);
}
return accountMap;
}
private Status defaultStatus(String personId, String domain, Date from) {
Status status = new Status();
status.setDomain(domain);
status.setPersonId(personId);
status.setStatus("");
status.setCreated(from);
status.setPeriod("today");
return status;
}
private Date parseDate(String from) throws ParseException {
if (from.startsWith("/"))
from = from.substring(1);
if (from.endsWith("/"))
from = from.substring(0, from.length());
return urlFormat.parse(from);
}
}
| true | true |
public String startNoPath(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
try {
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
if (null != host && host.contains(HOST_POSTFIX)) {
String personId = host.replace(HOST_POSTFIX, "");
if (!"www".equals(personId)) {
this.setModel(personId, null, model);
this.setViewer(request, model);
return "index/index";
}
}
} catch (MalformedURLException e) {
if (logger.isInfoEnabled())
logger.info("Unable to decode url from " + request.getRequestURL().toString());
}
String view = redirectIndex(request);
if (null == view)
view = "index/home";
return view;
}
|
public String startNoPath(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
try {
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
if (null != host && host.contains(HOST_POSTFIX)) {
String personId = host.replace(HOST_POSTFIX, "");
if (!"www".equals(personId)) {
this.setModel(personId, null, model);
this.setViewer(request, model);
return "index/index";
}
}
} catch (MalformedURLException e) {
if (logger.isInfoEnabled())
logger.info("Unable to decode url from " + request.getRequestURL().toString());
}
model.addAttribute("secureHost", secureHost());
String view = redirectIndex(request);
if (null == view)
view = "index/home";
return view;
}
|
diff --git a/containers/sip-servlets-jboss5/src/main/java/org/jboss/web/tomcat/service/session/ClusteredSipSession.java b/containers/sip-servlets-jboss5/src/main/java/org/jboss/web/tomcat/service/session/ClusteredSipSession.java
index fab8e0161..722434d06 100644
--- a/containers/sip-servlets-jboss5/src/main/java/org/jboss/web/tomcat/service/session/ClusteredSipSession.java
+++ b/containers/sip-servlets-jboss5/src/main/java/org/jboss/web/tomcat/service/session/ClusteredSipSession.java
@@ -1,1817 +1,1826 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.web.tomcat.service.session;
import gov.nist.javax.sip.message.RequestExt;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.sip.SipSessionActivationListener;
import javax.servlet.sip.SipSessionAttributeListener;
import javax.servlet.sip.SipSessionBindingEvent;
import javax.servlet.sip.SipSessionBindingListener;
import javax.servlet.sip.SipSessionEvent;
import javax.sip.Dialog;
import javax.sip.ServerTransaction;
import javax.sip.SipStack;
import javax.sip.Transaction;
import javax.sip.message.Request;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Service;
import org.apache.catalina.util.Enumerator;
import org.apache.catalina.util.StringManager;
import org.apache.log4j.Logger;
import org.jboss.metadata.web.jboss.ReplicationTrigger;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributableSipSessionMetadata;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributedCacheConvergedSipManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributedCacheManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.IncomingDistributableSessionData;
import org.jboss.web.tomcat.service.session.distributedcache.spi.OutgoingDistributableSessionData;
import org.jboss.web.tomcat.service.session.notification.ClusteredSessionManagementStatus;
import org.jboss.web.tomcat.service.session.notification.ClusteredSessionNotificationCause;
import org.jboss.web.tomcat.service.session.notification.ClusteredSipSessionNotificationPolicy;
import org.mobicents.ha.javax.sip.ClusteredSipStack;
import org.mobicents.ha.javax.sip.HASipDialog;
import org.mobicents.ha.javax.sip.ReplicationStrategy;
import org.mobicents.servlet.sip.GenericUtils;
import org.mobicents.servlet.sip.catalina.CatalinaSipManager;
import org.mobicents.servlet.sip.core.SipManager;
import org.mobicents.servlet.sip.core.SipService;
import org.mobicents.servlet.sip.core.message.MobicentsSipServletMessage;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSessionKey;
import org.mobicents.servlet.sip.core.session.SessionManagerUtil;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipSessionImpl;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.message.B2buaHelperImpl;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.message.TransactionApplicationData;
import org.mobicents.servlet.sip.notification.SessionActivationNotificationCause;
import org.mobicents.servlet.sip.notification.SipSessionActivationEvent;
import org.mobicents.servlet.sip.proxy.ProxyBranchImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.startup.StaticServiceHolder;
/**
* Abstract base class for sip session clustering based on SipSessionImpl. Different session
* replication strategy can be implemented such as session- field- or attribute-based ones.
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public abstract class ClusteredSipSession<O extends OutgoingDistributableSessionData> extends SipSessionImpl {
private static final Logger logger = Logger.getLogger(ClusteredSipSession.class);
protected static final String SESSION_TX_REQUEST = "str";
protected static final String IS_SESSION_TX_REQUEST_SERVER = "istrs";
protected static final String B2B_SESSION_MAP = "b2bsm";
protected static final String B2B_SESSION_SIZE = "b2bss";
protected static final String B2B_LINKED_REQUESTS_MAP = "b2blrm";
protected static final String B2B_LINKED_REQUESTS_SIZE = "b2blrs";
protected static final String TO_TAG = "tt";
protected static final String TXS_SIZE = "txm";
protected static final String TXS_IDS= "txid";
protected static final String TXS_TYPE= "txt";
protected static final String ACKS_RECEIVED_SIZE = "ars";
protected static final String ACKS_RECEIVED_CSEQ = "arc";
protected static final String ACKS_RECEIVED_VALUE= "arv";
protected static final String PROXY = "prox";
protected static final String DIALOG_ID = "did";
protected static final String READY_TO_INVALIDATE = "rti";
protected static final String INVALIDATE_WHEN_READY = "iwr";
protected static final String CSEQ = "cseq";
protected static final String STATE = "stat";
protected static final String IS_VALID = "iv";
protected static final String HANDLER = "hler";
protected static final String INVALIDATION_POLICY = "ip";
protected static final String CREATION_TIME = "ct";
protected static final String TRANSPORT = "tp";
protected static final boolean ACTIVITY_CHECK =
Globals.STRICT_SERVLET_COMPLIANCE
|| Boolean.valueOf(System.getProperty("org.apache.catalina.session.StandardSession.ACTIVITY_CHECK", "false")).booleanValue();
/**
* Descriptive information describing this Session implementation.
*/
protected static final String info = "ClusteredSipSession/1.0";
/**
* Set of attribute names which are not allowed to be replicated/persisted.
*/
protected static final String[] excludedAttributes = { Globals.SUBJECT_ATTR };
/**
* Set containing all members of {@link #excludedAttributes}.
*/
protected static final Set<String> replicationExcludes;
static {
Set<String> set = new HashSet<String>();
for (int i = 0; i < excludedAttributes.length; i++) {
set.add(excludedAttributes[i]);
}
replicationExcludes = Collections.unmodifiableSet(set);
}
/**
* The method signature for the <code>fireContainerEvent</code> method.
*/
protected static final Class<?> containerEventTypes[] = { String.class,
Object.class };
protected static final Logger log = Logger
.getLogger(ClusteredSession.class);
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager
.getManager(ClusteredSession.class.getPackage().getName());
// ----------------------------------------------------- Instance Variables
/**
* The collection of user data attributes associated with this Session.
*/
private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>(
16, 0.75f, 2);
/**
* The authentication type used to authenticate our cached Principal, if
* any. NOTE: This value is not included in the serialized version of this
* object.
*/
private transient String authType = null;
/**
* The <code>java.lang.Method</code> for the
* <code>fireContainerEvent()</code> method of the
* <code>org.apache.catalina.core.StandardContext</code> method, if our
* Context implementation is of this class. This value is computed
* dynamically the first time it is needed, or after a session reload (since
* it is declared transient).
*/
private transient Method containerEventMethod = null;
/**
* The Manager with which this Session is associated.
*/
private transient ClusteredSipManager<O> manager = null;
/**
* Our proxy to the distributed cache.
*/
private transient DistributedCacheConvergedSipManager<O> distributedCacheManager;
/**
* The maximum time interval, in seconds, between client requests before the
* servlet container may invalidate this session. A negative time indicates
* that the session should never time out.
*/
private int maxInactiveInterval = -1;
/**
* Flag indicating whether this session is new or not.
*/
private boolean isNew = false;
/**
* Internal notes associated with this session by Catalina components and
* event listeners. <b>IMPLEMENTATION NOTE:</b> This object is <em>not</em>
* saved and restored across session serializations!
*/
private final transient Map<String, Object> notes = new Hashtable<String, Object>();
/**
* The property change support for this component. NOTE: This value is not
* included in the serialized version of this object.
*/
private transient PropertyChangeSupport support =
new PropertyChangeSupport(this);
/**
* The current accessed time for this session.
*/
private volatile long thisAccessedTime = creationTime;
/**
* The access count for this session.
*/
private final transient AtomicInteger accessCount;
/**
* Policy controlling whether reading/writing attributes requires
* replication.
*/
private ReplicationTrigger invalidationPolicy;
/**
* If true, means the local in-memory session data contains metadata changes
* that have not been published to the distributed cache.
*/
private transient boolean sessionMetadataDirty;
/**
* If true, means the local in-memory session data contains attribute
* changes that have not been published to the distributed cache.
*/
private transient boolean sessionAttributesDirty;
/**
* Object wrapping thisAccessedTime. Create once and mutate so we can store
* it in JBoss Cache w/o concern that a transaction rollback will revert the
* cached ref to an older object.
*/
private final transient AtomicLong timestamp = new AtomicLong(0);
/**
* Object wrapping other metadata for this session. Create once and mutate
* so we can store it in JBoss Cache w/o concern that a transaction rollback
* will revert the cached ref to an older object.
*/
private volatile transient DistributableSipSessionMetadata metadata;
/**
* The last version that was passed to {@link #setDistributedVersion} or
* <code>0</code> if <code>setIsOutdated(false)</code> was subsequently
* called.
*/
private volatile transient int outdatedVersion;
/**
* The last time {@link #setIsOutdated setIsOutdated(true)} was called or
* <code>0</code> if <code>setIsOutdated(false)</code> was subsequently
* called.
*/
private volatile transient long outdatedTime;
/**
* Version number to track cache invalidation. If any new version number is
* greater than this one, it means the data it holds is newer than this one.
*/
private final AtomicInteger version = new AtomicInteger(0);
/**
* Whether JK is being used, in which case our realId will not match our id
*/
private transient boolean useJK;
/**
* Timestamp when we were last replicated.
*/
private volatile transient long lastReplicated;
/**
* Maximum number of milliseconds this session should be allowed to go
* unreplicated if access to the session doesn't mark it as dirty.
*/
private transient long maxUnreplicatedInterval;
/** True if maxUnreplicatedInterval is 0 or less than maxInactiveInterval */
private transient boolean alwaysReplicateTimestamp = false;
/**
* Whether any of this session's attributes implement
* HttpSessionActivationListener.
*/
private transient Boolean hasActivationListener;
/**
* Has this session only been accessed once?
*/
private transient boolean firstAccess;
/**
* Policy that drives whether we issue servlet spec notifications.
*/
//FIXME move the notfication policy to a SIP based one and not HTTP
private transient ClusteredSipSessionNotificationPolicy notificationPolicy;
private transient ClusteredSessionManagementStatus clusterStatus;
/**
* True if a call to activate() is needed to offset a preceding passivate()
* call
*/
private transient boolean needsPostReplicateActivation;
protected transient SipApplicationSessionKey sipAppSessionParentKey;
protected transient String sessionCreatingDialogId = null;
private transient String haId;
// ------------------------------------------------------------ Constructors
protected ClusteredSipSession(SipSessionKey key, SipFactoryImpl sipFactoryImpl, MobicentsSipApplicationSession mobicentsSipApplicationSession, boolean useJK) {
super(key, sipFactoryImpl, mobicentsSipApplicationSession);
haId = SessionManagerUtil.getSipSessionHaKey(key);
this.clusterStatus = new ClusteredSessionManagementStatus(haId, true, null, null);
if(mobicentsSipApplicationSession.getSipContext() != null) {
setManager((ClusteredSipManager)mobicentsSipApplicationSession.getSipContext().getSipManager());
this.invalidationPolicy = this.manager.getReplicationTrigger();
}
this.isNew = true;
this.useJK = useJK;
this.firstAccess = true;
updateThisAccessedTime();
accessCount = ACTIVITY_CHECK ? new AtomicInteger() : null;
// it starts with true so that it gets replicated when first created
sessionMetadataDirty = true;
metadata = new DistributableSipSessionMetadata();
this.metadata.setCreationTime(creationTime);
this.metadata.setNew(isNew);
this.metadata.setMaxInactiveInterval(maxInactiveInterval);
// checkAlwaysReplicateMetadata();
}
// ---------------------------------------------------------------- Session
public abstract String getInfo();
public String getAuthType() {
return (this.authType);
}
public void setAuthType(String authType) {
String oldAuthType = this.authType;
this.authType = authType;
support.firePropertyChange("authType", oldAuthType, this.authType);
}
public CatalinaSipManager getManager() {
return (this.manager);
}
public void setManager(SipManager manager) {
if ((manager instanceof ClusteredSipManager) == false)
throw new IllegalArgumentException(
"manager must implement ClusteredSipManager");
@SuppressWarnings("unchecked")
ClusteredSipManager<O> unchecked = (ClusteredSipManager) manager;
this.manager = unchecked;
this.invalidationPolicy = this.manager.getReplicationTrigger();
this.useJK = this.manager.getUseJK();
int maxUnrep = this.manager.getMaxUnreplicatedInterval() * 1000;
setMaxUnreplicatedInterval(maxUnrep);
this.notificationPolicy = this.manager.getSipSessionNotificationPolicy();
establishDistributedCacheManager();
}
public int getMaxInactiveInterval() {
return (this.maxInactiveInterval);
}
/**
* Overrides the superclass to calculate
* {@link #getMaxUnreplicatedInterval() maxUnreplicatedInterval}.
*/
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
if (isValid() && interval == 0) {
invalidate();
}
checkAlwaysReplicateTimestamp();
sessionMetadataDirty();
}
public void access() {
this.lastAccessedTime = this.thisAccessedTime;
this.thisAccessedTime = System.currentTimeMillis();
ConvergedSessionReplicationContext.bindSipSession(this, manager.getSnapshotSipManager());
if (ACTIVITY_CHECK) {
accessCount.incrementAndGet();
}
// JBAS-3528. If it's not the first access, make sure
// the 'new' flag is correct
// if (!firstAccess && isNew) {
// setNew(false);
// }
}
public void setNew(boolean isNew) {
this.isNew = isNew;
// Don't replicate metadata just 'cause its the second request
// The only effect of this is if someone besides a request
// deserializes metadata from the distributed cache, this
// field may be out of date.
// If a request accesses the session, the access() call will
// set isNew=false, so the request will see the correct value
// sessionMetadataDirty();
}
/**
* Invalidates this session and unbinds any objects bound to it. Overridden
* here to remove across the cluster instead of just expiring.
*
* @exception IllegalStateException
* if this method is called on an invalidated session
*/
public void invalidate() {
// if (!isValid())
// throw new IllegalStateException(sm
// .getString("clusteredSession.invalidate.ise"));
//
// // Cause this session to expire globally
// boolean notify = true;
// boolean localCall = true;
// boolean localOnly = false;
// invalidate(notify, localCall, localOnly,
// ClusteredSessionNotificationCause.INVALIDATE);
super.invalidate();
}
// /**
// * Expires the session, notifying listeners and possibly the manager.
// * <p>
// * <strong>NOTE:</strong> The manager will only be notified of the
// * expiration if <code>localCall</code> is <code>true</code>; otherwise it
// * is the responsibility of the caller to notify the manager that the
// * session is expired. (In the case of JBossCacheManager, it is the manager
// * itself that makes such a call, so it of course is aware).
// * </p>
// *
// * @param notify
// * whether servlet spec listeners should be notified
// * @param localCall
// * <code>true</code> if this call originated due to local
// * activity (such as a session invalidation in user code or an
// * expiration by the local background processing thread);
// * <code>false</code> if the expiration originated due to some
// * kind of event notification from the cluster.
// * @param localOnly
// * <code>true</code> if the expiration should not be announced to
// * the cluster, <code>false</code> if other cluster nodes should
// * be made aware of the expiration. Only meaningful if
// * <code>localCall</code> is <code>true</code>.
// * @param cause
// * the cause of the expiration
// */
// public void invalidate(boolean notify, boolean localCall,
// boolean localOnly, ClusteredSessionNotificationCause cause) {
// if (log.isTraceEnabled()) {
// log.trace("The session has been invalidated with key: " + key
// + " -- is invalidation local? " + localOnly);
// }
//
// synchronized (this) {
// // If we had a race to this sync block, another thread may
// // have already completed expiration. If so, don't do it again
// if (!isValid)
// return;
//
// if (manager == null)
// return;
//
// // Notify interested application event listeners
// // FIXME - Assumes we call listeners in reverse order
// Context context = (Context) manager.getContainer();
// Object lifecycleListeners[] = context
// .getApplicationLifecycleListeners();
// if (notify
// && (lifecycleListeners != null)
// && notificationPolicy
// .isSipSessionListenerInvocationAllowed(
// this.clusterStatus, cause, localCall)) {
// SipSessionEvent event = new SipSessionEvent(getSession());
// for (int i = 0; i < lifecycleListeners.length; i++) {
// int j = (lifecycleListeners.length - 1) - i;
// if (!(lifecycleListeners[j] instanceof SipSessionListener))
// continue;
// SipSessionListener listener = (SipSessionListener) lifecycleListeners[j];
// try {
// fireContainerEvent(context, "beforeSessionDestroyed",
// listener);
// listener.sessionDestroyed(event);
// fireContainerEvent(context, "afterSessionDestroyed",
// listener);
// } catch (Throwable t) {
// try {
// fireContainerEvent(context,
// "afterSessionDestroyed", listener);
// } catch (Exception e) {
// ;
// }
// manager.getContainer().getLogger().error(
// sm.getString("clusteredSession.sessionEvent"),
// t);
// }
// }
// }
//
// if (ACTIVITY_CHECK) {
// accessCount.set(0);
// }
//
// // Notify interested session event listeners.
//// if (notify) {
//// fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
//// }
//
// // JBAS-1360 -- Unbind any objects associated with this session
// String keys[] = keys();
// for (int i = 0; i < keys.length; i++) {
// removeAttributeInternal(keys[i], localCall, localOnly, notify,
// cause);
// }
//
// // Remove this session from our manager's active sessions
// // If !localCall, this expire call came from the manager,
// // so don't recurse
// if (localCall) {
// removeFromManager(localOnly);
// }
//
// }
//
// }
public Object getNote(String name) {
return (notes.get(name));
}
@SuppressWarnings("unchecked")
public Iterator getNoteNames() {
return (notes.keySet().iterator());
}
public void setNote(String name, Object value) {
notes.put(name, value);
}
public void removeNote(String name) {
notes.remove(name);
}
// ------------------------------------------------------------ HttpSession
public ServletContext getServletContext() {
if (manager == null)
return (null);
Context context = (Context) manager.getContainer();
if (context == null)
return (null);
else
return (context.getServletContext());
}
public Object getAttribute(String name) {
if (!isValid())
throw new IllegalStateException(sm
.getString("clusteredSession.getAttribute.ise"));
return getAttributeInternal(name);
}
@SuppressWarnings("unchecked")
public Enumeration getAttributeNames() {
if (!isValid())
throw new IllegalStateException(sm
.getString("clusteredSession.getAttributeNames.ise"));
return (new Enumerator(getAttributesInternal().keySet(), true));
}
public void setAttribute(String name, Object value) {
// Name cannot be null
if (name == null)
throw new IllegalArgumentException(sm
.getString("clusteredSession.setAttribute.namenull"));
// Null value is the same as removeAttribute()
if (value == null) {
removeAttribute(name);
return;
}
// Validate our current state
if (!isValid()) {
throw new IllegalStateException(sm
.getString("clusteredSession.setAttribute.ise"));
}
if (canAttributeBeReplicated(value) == false) {
throw new IllegalArgumentException(sm
.getString("clusteredSession.setAttribute.iae"));
}
// Construct an event with the new value
SipSessionBindingEvent event = null;
// Call the valueBound() method if necessary
if (value instanceof SipSessionBindingListener
&& notificationPolicy
.isSipSessionBindingListenerInvocationAllowed(
this.clusterStatus,
ClusteredSessionNotificationCause.MODIFY, name,
true)) {
event = new SipSessionBindingEvent(this, name);
try {
((SipSessionBindingListener) value).valueBound(event);
} catch (Throwable t) {
manager.getContainer().getLogger().error(
sm.getString("clusteredSession.bindingEvent"), t);
}
}
if (value instanceof SipSessionActivationListener)
hasActivationListener = Boolean.TRUE;
// Replace or add this attribute
Object unbound = setAttributeInternal(name, value);
// Call the valueUnbound() method if necessary
if ((unbound != null)
&& (unbound != value)
&& (unbound instanceof SipSessionBindingListener)
&& notificationPolicy
.isSipSessionBindingListenerInvocationAllowed(
this.clusterStatus,
ClusteredSessionNotificationCause.MODIFY, name,
true)) {
try {
((SipSessionBindingListener) unbound)
.valueUnbound(new SipSessionBindingEvent(this,
name));
} catch (Throwable t) {
manager.getContainer().getLogger().error(
sm.getString("clusteredSession.bindingEvent"), t);
}
}
// Notify interested application event listeners
if (notificationPolicy.isSipSessionAttributeListenerInvocationAllowed(
this.clusterStatus, ClusteredSessionNotificationCause.MODIFY,
name, true)) {
List<SipSessionAttributeListener> listeners = getSipApplicationSession().getSipContext().getListeners().getSipSessionAttributeListeners();
if (listeners == null)
return;
for (SipSessionAttributeListener listener : listeners) {
try {
if (unbound != null) {
// fireContainerEvent(context,
// "beforeSessionAttributeReplaced", listener);
if (event == null) {
event = new SipSessionBindingEvent(this, name);
}
listener.attributeReplaced(event);
// fireContainerEvent(context,
// "afterSessionAttributeReplaced", listener);
} else {
// fireContainerEvent(context, "beforeSessionAttributeAdded",
// listener);
if (event == null) {
event = new SipSessionBindingEvent(this, name);
}
listener.attributeAdded(event);
// fireContainerEvent(context, "afterSessionAttributeAdded",
// listener);
}
} catch (Throwable t) {
try {
// if (unbound != null) {
// fireContainerEvent(context,
// "afterSessionAttributeReplaced", listener);
// } else {
// fireContainerEvent(context,
// "afterSessionAttributeAdded", listener);
// }
} catch (Exception e) {
;
}
logger.error(
sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
@Override
public void removeAttribute(String name, boolean byPassValidCheck) {
// Validate our current state
if (!byPassValidCheck && !isValid())
throw new IllegalStateException(sm
.getString("clusteredSession.removeAttribute.ise"));
final boolean localCall = true;
final boolean localOnly = false;
final boolean notify = true;
removeAttributeInternal(name, localCall, localOnly, notify,
ClusteredSessionNotificationCause.MODIFY);
}
public Object getValue(String name) {
return (getAttribute(name));
}
public void putValue(String name, Object value) {
setAttribute(name, value);
}
public void removeValue(String name) {
removeAttribute(name);
}
// ---------------------------------------------------- DistributableSession
protected int getVersion() {
return version.get();
}
public boolean getMustReplicateTimestamp() {
boolean exceeds = alwaysReplicateTimestamp;
if (!exceeds && maxUnreplicatedInterval > 0) // -1 means ignore
{
long unrepl = System.currentTimeMillis() - lastReplicated;
exceeds = (unrepl >= maxUnreplicatedInterval);
}
return exceeds;
}
protected long getSessionTimestamp() {
this.timestamp.set(this.thisAccessedTime);
return this.timestamp.get();
}
public void updateThisAccessedTime() {
thisAccessedTime = System.currentTimeMillis();
}
protected boolean isSessionMetadataDirty() {
return sessionMetadataDirty;
}
protected DistributableSipSessionMetadata getSessionMetadata() {
return this.metadata;
}
protected boolean isSessionAttributeMapDirty() {
return sessionAttributesDirty;
}
/**
* {@inheritDoc}
*/
public void update(IncomingDistributableSessionData sessionData) {
assert sessionData != null : "sessionData is null";
this.version.set(sessionData.getVersion());
long ts = sessionData.getTimestamp();
this.lastAccessedTime = this.thisAccessedTime = ts;
this.timestamp.set(ts);
this.metadata = (DistributableSipSessionMetadata)sessionData.getMetadata();
// TODO -- get rid of these field and delegate to metadata
this.creationTime = metadata.getCreationTime();
this.maxInactiveInterval = metadata.getMaxInactiveInterval();
updateSipSession(metadata);
// We no longer know if we have an activationListener
hasActivationListener = null;
// If the session has been replicated, any subsequent
// access cannot be the first.
this.firstAccess = false;
// We don't know when we last replicated our timestamp. We may be
// getting called due to activation, not deserialization after
// replication, so this.timestamp may be after the last replication.
// So use the creation time as a conservative guesstimate. Only downside
// is we may replicate a timestamp earlier than we need to, which is not
// a heavy cost.
this.lastReplicated = this.creationTime;
this.clusterStatus = new ClusteredSessionManagementStatus(haId,
true, null, null);
checkAlwaysReplicateTimestamp();
populateAttributes(sessionData.getSessionAttributes());
isNew = false;
// We are no longer outdated vis a vis distributed cache
clearOutdated();
// make sure we don't write back to the cache on a remote session refresh
sessionAttributesDirty = false;
sessionMetadataDirty = false;
}
protected void updateSipSession(DistributableSipSessionMetadata md) {
//From SipSession
final Map<String, Object> metaData = md.getMetaData();
handlerServlet = (String) metaData.get(HANDLER);
Boolean valid = (Boolean)metaData.get(IS_VALID);
if(valid != null) {
// call to super very important to avoid setting the session dirty on reload and rewrite to the cache
super.setValid(valid);
}
state = (State)metaData.get(STATE);
+ if(logger.isDebugEnabled()) {
+ logger.debug("replicated sip session state = " + state);
+ }
+ // http://code.google.com/p/sipservlets/issues/detail?id=42
+ // in case of REGISTER (or out of dialog requests) , the state will have stayed INITIAL
+ // and as such not changed so not replicated, thus if state is null we default to INITIAL
+ if(state == null) {
+ state = State.INITIAL;
+ }
Long cSeq = (Long) metaData.get(CSEQ);
if(cSeq != null) {
cseq = cSeq;
}
Boolean iwr = (Boolean) metaData.get(INVALIDATE_WHEN_READY);
if(iwr != null) {
invalidateWhenReady = iwr;
}
Boolean rti = (Boolean) metaData.get(READY_TO_INVALIDATE);
if(rti != null) {
readyToInvalidate = rti;
}
sessionCreatingDialogId = (String) metaData.get(DIALOG_ID);
proxy = (ProxyImpl) metaData.get(PROXY);
if(proxy != null) {
proxy.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
}
transport = (String) metaData.get(TRANSPORT);
Integer size = (Integer) metaData.get(B2B_SESSION_SIZE);
String[][] sessionArray = (String[][])metaData.get(B2B_SESSION_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua session array size = " + size + ", value = " + sessionArray);
}
if(size != null && sessionArray != null) {
Map<MobicentsSipSessionKey, MobicentsSipSessionKey> sessionMap = new ConcurrentHashMap<MobicentsSipSessionKey, MobicentsSipSessionKey>();
for (int i = 0; i < size; i++) {
String key = sessionArray[0][i];
String value = sessionArray[1][i];
try {
SipSessionKey sipSessionKeyKey = SessionManagerUtil.parseSipSessionKey(key);
SipSessionKey sipSessionKeyValue = SessionManagerUtil.parseSipSessionKey(value);
sessionMap.put(sipSessionKeyKey, sipSessionKeyValue);
} catch (ParseException e) {
logger.warn("couldn't parse a deserialized sip session key from the B2BUA", e);
}
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setSessionMap(sessionMap);
}
SipServletRequestImpl sessionRequest = (SipServletRequestImpl) metaData.get(SESSION_TX_REQUEST);
if(logger.isDebugEnabled()) {
logger.debug("session transaction creation request = " + sessionRequest);
}
if(sessionRequest != null) {
sessionCreatingTransactionRequest = sessionRequest;
}
Boolean isSessionStx = (Boolean) metaData.get(IS_SESSION_TX_REQUEST_SERVER);
if(logger.isDebugEnabled()) {
logger.debug("is session transaction creation server = " + isSessionStx);
}
if(isSessionStx != null) {
isSessionCreatingTransactionServer = isSessionCreatingTransactionServer;
}
if(((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).getReplicationStrategy() == ReplicationStrategy.EarlyDialog) {
Integer txsSize = (Integer) metaData.get(TXS_SIZE);
String[] txIds = (String[])metaData.get(TXS_IDS);
Boolean[] txTypes = (Boolean[])metaData.get(TXS_TYPE);
if(logger.isDebugEnabled()) {
logger.debug("tx array size = " + txsSize + ", value = " + txIds);
}
if(txsSize != null && txIds != null) {
for (int i = 0; i < txsSize; i++) {
String txId = txIds[i];
Boolean txType = txTypes[i];
if(logger.isDebugEnabled()) {
logger.debug("trying to find tx with id = " + txId + ", type = " + txType + " locally or in the distributed cache");
}
Transaction transaction = ((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).findTransaction(txId, txType);
addOngoingTransaction(transaction);
if(transaction != null) {
if(transaction instanceof ServerTransaction) {
acksReceived.put(((RequestExt)transaction.getRequest()).getCSeqHeader().getSeqNumber(), false);
} else if(proxy != null) {
final TransactionApplicationData transactionApplicationData = (TransactionApplicationData) transaction.getApplicationData();
if(logger.isDebugEnabled()) {
logger.debug("transaction application data from tx id " + txId + " is " + transactionApplicationData);
}
if(transactionApplicationData != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating proxy from the transaction application data");
}
proxy.getTransactionMap().put(txId, transactionApplicationData);
ProxyBranchImpl proxyBranchImpl = transactionApplicationData.getProxyBranch();
if(proxyBranchImpl != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating branch from the transaction application data");
}
proxyBranchImpl.setOutgoingRequest((SipServletRequestImpl)transactionApplicationData.getSipServletMessage());
proxyBranchImpl.setOriginalRequest((SipServletRequestImpl)proxy.getOriginalRequest());
proxyBranchImpl.setProxy(proxy);
proxy.addProxyBranch(proxyBranchImpl);
}
}
}
}
}
}
String toTag = (String) metaData.get(TO_TAG);
if(logger.isDebugEnabled()) {
logger.debug("sessionkey replicated totag to " + toTag);
}
if(key.getToTag() == null && toTag != null && toTag.trim().length() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("setting sessionkey totag to " + toTag);
}
key.setToTag(toTag, false);
}
// Fix for Issue 2739 : Null returned for B2BUAHelperImpl.getLinkedSipServletRequest() in Early Dailog Failover
size = (Integer) metaData.get(B2B_LINKED_REQUESTS_SIZE);
SipServletRequestImpl[][] linkedRequests = (SipServletRequestImpl[][])metaData.get(B2B_LINKED_REQUESTS_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua linked requests array size = " + size + ", value = " + linkedRequests);
}
if(size != null && linkedRequests != null) {
Map<SipServletRequestImpl, SipServletRequestImpl> linkedRequestsMap = new ConcurrentHashMap<SipServletRequestImpl, SipServletRequestImpl>();
for (int i = 0; i < size; i++) {
SipServletRequestImpl key = linkedRequests[0][i];
SipServletRequestImpl value = linkedRequests[1][i];
linkedRequestsMap.put(key, value);
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setOriginalRequestMap(linkedRequestsMap);
}
}
if(logger.isDebugEnabled()) {
logger.debug("dialog to inject " + sessionCreatingDialogId);
if(sessionCreatingDialogId != null) {
logger.debug("dialog id of the dialog to inject " + sessionCreatingDialogId);
}
}
if(sessionCreatingDialogId != null && sessionCreatingDialogId.length() > 0) {
Container context = getManager().getContainer();
Container container = context.getParent().getParent();
if(container instanceof Engine) {
Service service = ((Engine)container).getService();
if(service instanceof SipService) {
SipService sipService = (SipService) service;
SipStack sipStack = sipService.getSipStack();
if(sipStack != null) {
sessionCreatingDialog = ((ClusteredSipStack)sipStack).getDialog(sessionCreatingDialogId);
if(logger.isDebugEnabled()) {
logger.debug("dialog injected " + sessionCreatingDialog);
}
}
}
}
}
}
// ------------------------------------------------------------------ Public
/**
* Increment our version and propagate ourself to the distributed cache.
*/
public void processSipSessionReplication() {
// Replicate the session.
if (log.isDebugEnabled()) {
log
.debug("processSipSessionReplication(): session is dirty. Will increment "
+ "version from: "
+ getVersion()
+ " and replicate.");
}
version.incrementAndGet();
O outgoingData = getOutgoingSipSessionData();
if(sessionMetadataDirty) {
Map<String, Object> metaData = ((DistributableSipSessionMetadata)outgoingData.getMetadata()).getMetaData();
if(proxy != null) {
metaData.put(PROXY, proxy);
}
if(b2buaHelper != null) {
final Map<MobicentsSipSessionKey, MobicentsSipSessionKey> sessionMap = b2buaHelper.getSessionMap();
final int size = sessionMap.size();
final String[][] sessionArray = new String[2][size];
int i = 0;
for (Entry<MobicentsSipSessionKey, MobicentsSipSessionKey> entry : sessionMap.entrySet()) {
sessionArray [0][i] = entry.getKey().toString();
sessionArray [1][i] = entry.getValue().toString();
i++;
}
metaData.put(B2B_SESSION_SIZE, size);
if(logger.isDebugEnabled()) {
logger.debug("storing b2bua session array " + sessionArray);
}
metaData.put(B2B_SESSION_MAP, sessionArray);
}
// http://code.google.com/p/mobicents/issues/detail?id=2799 since REGISTER always stays in INITIAL state there is a dedicated check
if(State.INITIAL.equals(state) && sessionCreatingDialog == null && sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getMethod().equalsIgnoreCase(Request.REGISTER)) {
metaData.put(SESSION_TX_REQUEST, sessionCreatingTransactionRequest);
metaData.put(IS_SESSION_TX_REQUEST_SERVER, isSessionCreatingTransactionServer);
}
if(((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).getReplicationStrategy() == ReplicationStrategy.EarlyDialog) {
final Set<Transaction> ongoingTransactions = getOngoingTransactions();
final int size = ongoingTransactions.size();
final String[] txIdArray = new String[size];
final Boolean[] txTypeArray = new Boolean[size];
int i = 0;
for (Transaction transaction : ongoingTransactions) {
txIdArray[i] = transaction.getBranchId();
txTypeArray[i] = transaction instanceof ServerTransaction ? Boolean.TRUE : Boolean.FALSE;
i++;
}
metaData.put(TXS_SIZE, size);
if(logger.isDebugEnabled()) {
logger.debug("storing transaction ids array " + txIdArray);
}
metaData.put(TXS_IDS, txIdArray);
if(logger.isDebugEnabled()) {
logger.debug("storing transaction type array " + txTypeArray);
}
metaData.put(TXS_TYPE, txTypeArray);
String toTag = key.getToTag();
if(toTag == null) {
toTag = "";
}
if(logger.isDebugEnabled()) {
logger.debug("storing session key toTag " + toTag);
}
metaData.put(TO_TAG, toTag);
if(b2buaHelper != null) {
// Fix for Issue 2739 : Null returned for B2BUAHelperImpl.getLinkedSipServletRequest() in Early Dailog Failover
final Map<SipServletRequestImpl, SipServletRequestImpl> linkedRequestsMap = b2buaHelper.getOriginalRequestMap();
final int linkedRequestsMapSize = linkedRequestsMap.size();
final SipServletRequestImpl[][] linkedRequestsArray = new SipServletRequestImpl[2][linkedRequestsMapSize];
int j = 0;
for (Entry<SipServletRequestImpl, SipServletRequestImpl> entry : linkedRequestsMap.entrySet()) {
linkedRequestsArray [0][j] = entry.getKey();
linkedRequestsArray [1][j] = entry.getValue();
j++;
}
metaData.put(B2B_LINKED_REQUESTS_SIZE, linkedRequestsMapSize);
if(logger.isDebugEnabled()) {
logger.debug("storing b2bua linked requests array " + linkedRequestsArray);
}
metaData.put(B2B_LINKED_REQUESTS_MAP, linkedRequestsArray);
}
}
}
distributedCacheManager.storeSipSessionData(outgoingData);
sessionAttributesDirty = false;
sessionMetadataDirty = false;
isNew = false;
metadata.setNew(isNew);
metadata.getMetaData().clear();
lastReplicated = System.currentTimeMillis();
}
protected abstract O getOutgoingSipSessionData();
/**
* Remove myself from the distributed cache.
*/
public void removeMyself() {
((DistributedCacheConvergedSipManager)getDistributedCacheManager()).removeSipSession(sipApplicationSessionKey.getId(), SessionManagerUtil.getSipSessionHaKey(key));
}
/**
* Remove myself from the <t>local</t> instance of the distributed cache.
*/
public void removeMyselfLocal() {
((DistributedCacheConvergedSipManager)getDistributedCacheManager()).removeSipSessionLocal(sipApplicationSessionKey.getId(), SessionManagerUtil.getSipSessionHaKey(key), null);
}
/**
* Gets the sessions creation time, skipping any validity check.
*
* @return the creation time
*/
public long getCreationTimeInternal() {
return creationTime;
}
/**
* Gets the time {@link #processSessionReplication()} was last called, or
* <code>0</code> if it has never been called.
*/
public long getLastReplicated() {
return lastReplicated;
}
/**
* Gets the maximum period in ms after which a request accessing this
* session will trigger replication of its timestamp, even if the request
* doesn't otherwise modify the session. A value of -1 means no limit.
*/
public long getMaxUnreplicatedInterval() {
return maxUnreplicatedInterval;
}
/**
* Sets the maximum period in ms after which a request accessing this
* session will trigger replication of its timestamp, even if the request
* doesn't otherwise modify the session. A value of -1 means no limit.
*/
public void setMaxUnreplicatedInterval(long interval) {
this.maxUnreplicatedInterval = Math.max(interval, -1);
checkAlwaysReplicateTimestamp();
}
/**
* Gets whether the session expects to be accessible via mod_jk, mod_proxy,
* mod_cluster or other such AJP-based load balancers.
*/
public boolean getUseJK() {
return useJK;
}
/**
* Update our version due to changes in the distributed cache.
*
* @param version
* the distributed cache version
* @return <code>true</code>
*/
public boolean setVersionFromDistributedCache(int version) {
boolean outdated = getVersion() < version;
if (outdated) {
this.outdatedVersion = version;
outdatedTime = System.currentTimeMillis();
}
return outdated;
}
/**
* Check to see if the session data is still valid. Outdated here means that
* the in-memory data is not in sync with one in the data store.
*
* @return
*/
public boolean isOutdated() {
return thisAccessedTime < outdatedTime;
}
public boolean isSessionDirty() {
return sessionAttributesDirty || sessionMetadataDirty;
}
/** Inform any SipApplicationSessionActivationListener of the activation of this session */
public void tellActivation(SessionActivationNotificationCause cause) {
if(attributes != null) {
for(Entry<String, Object> attribute : attributes.entrySet()) {
SipSessionActivationEvent sipSessionEvent = new SipSessionActivationEvent(this, cause);
if(attribute.getValue() instanceof SipSessionActivationListener) {
if (notificationPolicy.isSipSessionActivationListenerInvocationAllowed(
this.clusterStatus, cause, attribute.getKey())) {
ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader();
java.lang.Thread.currentThread().setContextClassLoader(getSipApplicationSession().getSipContext().getSipContextClassLoader());
try {
if(logger.isDebugEnabled()) {
logger.debug("notifying sip session activation listener " + attribute.getValue() + " of sip session activation " +
key);
}
((SipSessionActivationListener)attribute.getValue()).sessionDidActivate(sipSessionEvent);
} catch (Throwable t) {
logger.error("SipSessionActivationListener " + attribute.getValue() + " threw exception", t);
}
java.lang.Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
}
}
private String[] keys() {
Set<String> keySet = getAttributesInternal().keySet();
return ((String[]) keySet.toArray(new String[keySet.size()]));
}
/**
* Inform any HttpSessionActivationListener that the session will passivate.
*
* @param cause
* cause of the notification (e.g.
* {@link ClusteredSessionNotificationCause#REPLICATION} or
* {@link ClusteredSessionNotificationCause#PASSIVATION}
*/
public void notifyWillPassivate(SessionActivationNotificationCause cause) {
// Notify interested session event listeners
// fireSessionEvent(Session.SESSION_PASSIVATED_EVENT, null);
if (hasActivationListener != null && hasActivationListener != Boolean.FALSE) {
boolean hasListener = false;
// Notify ActivationListeners
SipSessionEvent event = null;
String keys[] = keys();
Map<String, Object> attrs = getAttributesInternal();
for (int i = 0; i < keys.length; i++) {
Object attribute = attrs.get(keys[i]);
if (attribute instanceof SipSessionActivationListener) {
hasListener = true;
if (notificationPolicy
.isSipSessionActivationListenerInvocationAllowed(
this.clusterStatus, cause, keys[i])) {
if (event == null)
event = new SipSessionActivationEvent(this, cause);
ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader();
java.lang.Thread.currentThread().setContextClassLoader(getSipApplicationSession().getSipContext().getSipContextClassLoader());
try {
((SipSessionActivationListener) attribute)
.sessionWillPassivate(event);
} catch (Throwable t) {
manager
.getContainer()
.getLogger()
.error(
sm
.getString("clusteredSession.attributeEvent"),
t);
}
java.lang.Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
hasActivationListener = hasListener ? Boolean.TRUE : Boolean.FALSE;
}
if (cause != SessionActivationNotificationCause.PASSIVATION) {
this.needsPostReplicateActivation = true;
}
}
/**
* Inform any HttpSessionActivationListener that the session has been
* activated.
*
* @param cause
* cause of the notification (e.g.
* {@link ClusteredSessionNotificationCause#REPLICATION} or
* {@link ClusteredSessionNotificationCause#PASSIVATION}
*/
public void notifyDidActivate(SessionActivationNotificationCause cause) {
if (cause == SessionActivationNotificationCause.ACTIVATION) {
this.needsPostReplicateActivation = true;
}
// Notify interested session event listeners
// fireSessionEvent(Session.SESSION_ACTIVATED_EVENT, null);
if (hasActivationListener != Boolean.FALSE) {
// Notify ActivationListeners
boolean hasListener = false;
SipSessionEvent event = null;
String keys[] = keys();
Map<String, Object> attrs = getAttributesInternal();
for (int i = 0; i < keys.length; i++) {
Object attribute = attrs.get(keys[i]);
if (attribute instanceof SipSessionActivationListener) {
hasListener = true;
if (notificationPolicy
.isSipSessionActivationListenerInvocationAllowed(
this.clusterStatus, cause, keys[i])) {
if (event == null)
event = new SipSessionActivationEvent(this, cause);
ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader();
java.lang.Thread.currentThread().setContextClassLoader(getSipApplicationSession().getSipContext().getSipContextClassLoader());
try {
((SipSessionActivationListener) attribute)
.sessionDidActivate(event);
} catch (Throwable t) {
manager
.getContainer()
.getLogger()
.error(
sm
.getString("clusteredSession.attributeEvent"),
t);
}
java.lang.Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
hasActivationListener = hasListener ? Boolean.TRUE : Boolean.FALSE;
}
if (cause != SessionActivationNotificationCause.ACTIVATION) {
this.needsPostReplicateActivation = false;
}
}
/**
* Gets whether the session needs to notify HttpSessionActivationListeners
* that it has been activated following replication.
*/
public boolean getNeedsPostReplicateActivation() {
return needsPostReplicateActivation;
}
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName()).append('[')
.append("id: ").append(haId).append(" lastAccessedTime: ")
.append(lastAccessedTime).append(" version: ").append(version)
.append(" lastOutdated: ").append(outdatedTime).append(']')
.toString();
}
// ----------------------------------------------------- Protected Methods
protected abstract Object setAttributeInternal(String name, Object value);
protected abstract Object removeAttributeInternal(String name,
boolean localCall, boolean localOnly);
protected Object getAttributeInternal(String name) {
Object result = getAttributesInternal().get(name);
// Do dirty check even if result is null, as w/ SET_AND_GET null
// still makes us dirty (ensures timely replication w/o using ACCESS)
if (isGetDirty(result)) {
sessionAttributesDirty();
}
return result;
}
/**
* Extension point for subclasses to load the attribute map from the
* distributed cache.
*/
protected void populateAttributes(
Map<String, Object> distributedCacheAttributes) {
Map<String, Object> existing = getAttributesInternal();
Map<String, Object> excluded = removeExcludedAttributes(existing);
existing.clear();
if(logger.isDebugEnabled()) {
logger.debug("putting following attributes " + distributedCacheAttributes + " in the sip session " + key);
}
existing.putAll(distributedCacheAttributes);
if (excluded != null)
existing.putAll(excluded);
}
protected final Map<String, Object> getAttributesInternal() {
return attributes;
}
protected final ClusteredSipManager<O> getManagerInternal() {
return manager;
}
protected final DistributedCacheManager<O> getDistributedCacheManager() {
return distributedCacheManager;
}
protected final void setDistributedCacheManager(
DistributedCacheConvergedSipManager<O> distributedCacheManager) {
this.distributedCacheManager = distributedCacheManager;
}
/**
* Returns whether the attribute's type is one that can be replicated.
*
* @param attribute
* the attribute
* @return <code>true</code> if <code>attribute</code> is <code>null</code>,
* <code>Serializable</code> or an array of primitives.
*/
protected boolean canAttributeBeReplicated(Object attribute) {
if (attribute instanceof Serializable || attribute == null)
return true;
Class<?> clazz = attribute.getClass().getComponentType();
return (clazz != null && clazz.isPrimitive());
}
/**
* Removes any attribute whose name is found in {@link #excludedAttributes}
* from <code>attributes</code> and returns a Map of all such attributes.
*
* @param attributes
* source map from which excluded attributes are to be removed.
*
* @return Map that contains any attributes removed from
* <code>attributes</code>, or <code>null</code> if no attributes
* were removed.
*/
protected final Map<String, Object> removeExcludedAttributes(
Map<String, Object> attributes) {
Map<String, Object> excluded = null;
for (int i = 0; i < excludedAttributes.length; i++) {
Object attr = attributes.remove(excludedAttributes[i]);
if (attr != null) {
if (log.isTraceEnabled()) {
log.trace("Excluding attribute " + excludedAttributes[i]
+ " from replication");
}
if (excluded == null) {
excluded = new HashMap<String, Object>();
}
excluded.put(excludedAttributes[i], attr);
}
}
return excluded;
}
protected final boolean isGetDirty(Object attribute) {
boolean result = false;
switch (invalidationPolicy) {
case SET_AND_GET:
result = true;
break;
case SET_AND_NON_PRIMITIVE_GET:
result = isMutable(attribute);
break;
default:
// result is false
}
return result;
}
protected boolean isMutable(Object attribute) {
return attribute != null
&& !(attribute instanceof String || attribute instanceof Number
|| attribute instanceof Character || attribute instanceof Boolean);
}
/**
* Gets a reference to the JBossCacheService.
*/
protected void establishDistributedCacheManager() {
if (distributedCacheManager == null) {
distributedCacheManager = getManagerInternal()
.getDistributedCacheConvergedSipManager();
// still null???
if (distributedCacheManager == null) {
throw new RuntimeException("DistributedCacheManager is null.");
}
}
}
protected final void sessionAttributesDirty() {
if (!sessionAttributesDirty && log.isDebugEnabled()) {
log.debug("Marking session attributes dirty " + haId);
log.debug(GenericUtils.makeStackTrace());
}
sessionAttributesDirty = true;
ConvergedSessionReplicationContext.bindSipSession(this, manager.getSnapshotSipManager());
}
protected final void setHasActivationListener(boolean hasListener) {
this.hasActivationListener = Boolean.valueOf(hasListener);
}
// ----------------------------------------------------------------- Private
private void checkAlwaysReplicateTimestamp() {
this.alwaysReplicateTimestamp = (maxUnreplicatedInterval == 0 || (maxUnreplicatedInterval > 0
&& maxInactiveInterval >= 0 && maxUnreplicatedInterval > (maxInactiveInterval * 1000)));
}
/**
* Remove the attribute from the local cache and possibly the distributed
* cache, plus notify any listeners
*
* @param name
* the attribute name
* @param localCall
* <code>true</code> if this call originated from local activity
* (e.g. a removeAttribute() in the webapp or a local session
* invalidation/expiration), <code>false</code> if it originated
* due to an remote event in the distributed cache.
* @param localOnly
* <code>true</code> if the removal should not be replicated
* around the cluster
* @param notify
* <code>true</code> if listeners should be notified
* @param cause
* the cause of the removal
*/
private void removeAttributeInternal(String name, boolean localCall,
boolean localOnly, boolean notify,
ClusteredSessionNotificationCause cause) {
// Remove this attribute from our collection
Object value = removeAttributeInternal(name, localCall, localOnly);
// Do we need to do valueUnbound() and attributeRemoved() notification?
if (!notify || (value == null)) {
return;
}
// Call the valueUnbound() method if necessary
SipSessionBindingEvent event = null;
if (value instanceof SipSessionBindingListener
&& notificationPolicy
.isSipSessionBindingListenerInvocationAllowed(
this.clusterStatus, cause, name, localCall)) {
event = new SipSessionBindingEvent(this, name);
((SipSessionBindingListener) value).valueUnbound(event);
}
// Notify interested application event listeners
if (notificationPolicy.isSipSessionAttributeListenerInvocationAllowed(
this.clusterStatus, cause, name, localCall)) {
// Notify interested application event listeners
List<SipSessionAttributeListener> listeners = getSipApplicationSession().getSipContext().getListeners().getSipSessionAttributeListeners();
if (listeners == null)
return;
for (SipSessionAttributeListener listener : listeners) {
try {
// fireContainerEvent(context, "beforeSessionAttributeRemoved",
// listener);
if (event == null) {
event = new SipSessionBindingEvent(this, name);
}
listener.attributeRemoved(event);
// fireContainerEvent(context, "afterSessionAttributeRemoved",
// listener);
} catch (Throwable t) {
// try {
// fireContainerEvent(context, "afterSessionAttributeRemoved",
// listener);
// } catch (Exception e) {
// ;
// }
logger.error(
sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
/**
* Fire container events if the Context implementation is the
* <code>org.apache.catalina.core.StandardContext</code>.
*
* @param context
* Context for which to fire events
* @param type
* Event type
* @param data
* Event data
*
* @exception Exception
* occurred during event firing
*/
private void fireContainerEvent(Context context, String type, Object data)
throws Exception {
if (!"org.apache.catalina.core.StandardContext".equals(context
.getClass().getName())) {
return; // Container events are not supported
}
// NOTE: Race condition is harmless, so do not synchronize
if (containerEventMethod == null) {
containerEventMethod = context.getClass().getMethod(
"fireContainerEvent", containerEventTypes);
}
Object containerEventParams[] = new Object[2];
containerEventParams[0] = type;
containerEventParams[1] = data;
containerEventMethod.invoke(context, containerEventParams);
}
private void sessionMetadataDirty() {
// if (!sessionMetadataDirty && !isNew && log.isTraceEnabled())
if(log.isDebugEnabled()) {
log.debug("Marking sip session metadata dirty " + key);
}
sessionMetadataDirty = true;
ConvergedSessionReplicationContext.bindSipSession(this, manager.getSnapshotSipManager());
}
/**
* Advise our manager to remove this expired session.
*
* @param localOnly
* whether the rest of the cluster should be made aware of the
* removal
*/
private void removeFromManager(boolean localOnly) {
if (localOnly) {
manager.removeLocal(this);
} else {
manager.removeSipSession(key);
}
}
public final void clearOutdated() {
// Only overwrite the access time if access() hasn't been called
// since setOutdatedVersion() was called
if (outdatedTime > thisAccessedTime) {
lastAccessedTime = thisAccessedTime;
thisAccessedTime = outdatedTime;
}
outdatedTime = 0;
// Only overwrite the version if the outdated version is greater
// Otherwise when we first unmarshall a session that has been
// replicated many times, we will reset the version to 0
if (outdatedVersion > version.get())
version.set(outdatedVersion);
outdatedVersion = 0;
}
@Override
public void setState(State state) {
super.setState(state);
sessionMetadataDirty();
metadata.getMetaData().put(STATE, state);
}
@Override
public void setCseq(long cseq) {
long oldCSeq = getCseq();
super.setCseq(cseq);
if(oldCSeq != cseq) {
sessionMetadataDirty();
metadata.getMetaData().put(CSEQ, cseq);
}
}
@Override
public void setHandler(String name) throws ServletException {
super.setHandler(name);
sessionMetadataDirty();
metadata.getMetaData().put(HANDLER, name);
}
@Override
public void setInvalidateWhenReady(boolean arg0) {
super.setInvalidateWhenReady(arg0);
sessionMetadataDirty();
metadata.getMetaData().put(INVALIDATE_WHEN_READY, arg0);
}
@Override
public void setReadyToInvalidate(boolean readyToInvalidate) {
boolean oldReadyToInvalidate = this.readyToInvalidate;
super.setReadyToInvalidate(readyToInvalidate);
if(oldReadyToInvalidate != readyToInvalidate) {
sessionMetadataDirty();
metadata.getMetaData().put(READY_TO_INVALIDATE, readyToInvalidate);
}
}
@Override
public void setValid(boolean isValid) {
super.setValid(isValid);
sessionMetadataDirty();
metadata.getMetaData().put(IS_VALID, isValid);
}
// http://code.google.com/p/sipservlets/issues/detail?id=42
@Override
public void setSessionCreatingTransactionRequest(
MobicentsSipServletMessage message) {
super.setSessionCreatingTransactionRequest(message);
if(State.INITIAL.equals(state) && sessionCreatingDialog == null && sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getMethod().equalsIgnoreCase(Request.REGISTER)) {
sessionMetadataDirty();
}
}
@Override
public void setSessionCreatingDialog(Dialog dialog) {
if(log.isDebugEnabled()) {
if(super.sessionCreatingDialog != null) {
log.debug(" oldDialogId " + sessionCreatingDialogId);
}
}
super.setSessionCreatingDialog(dialog);
if(log.isDebugEnabled()) {
log.debug(" dialog " + dialog);
if(dialog != null) {
log.debug(" dialogId " + dialog.getDialogId());
}
}
if(dialog != null && dialog.getDialogId() != null && !dialog.getDialogId().equals(sessionCreatingDialogId)) {
if(dialog != null) {
log.debug("DialogId set to " + dialog.getDialogId());
}
sessionMetadataDirty();
metadata.getMetaData().put(DIALOG_ID, dialog.getDialogId() );
sessionCreatingDialogId = dialog.getDialogId();
}
}
@Override
public void setTransport(String transport) {
super.setTransport(transport);
sessionMetadataDirty();
metadata.getMetaData().put(TRANSPORT, transport );
}
public String getHaId() {
return haId;
}
@Override
public void passivate() {
notifyWillPassivate(SessionActivationNotificationCause.PASSIVATION);
processDialogPassivation();
sipApplicationSession = null;
}
public void processDialogPassivation() {
if(sessionCreatingDialog != null) {
((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).passivateDialog((HASipDialog)sessionCreatingDialog);
TransactionApplicationData applicationData = ((TransactionApplicationData)sessionCreatingDialog.getApplicationData());
if(applicationData != null) {
applicationData.cleanUp();
applicationData.getSipServletMessage().cleanUp();
applicationData.getSipServletMessage().setSipSession(null);
sessionCreatingDialog.setApplicationData(null);
}
}
sessionCreatingDialog = null;
}
}
| true | true |
protected void updateSipSession(DistributableSipSessionMetadata md) {
//From SipSession
final Map<String, Object> metaData = md.getMetaData();
handlerServlet = (String) metaData.get(HANDLER);
Boolean valid = (Boolean)metaData.get(IS_VALID);
if(valid != null) {
// call to super very important to avoid setting the session dirty on reload and rewrite to the cache
super.setValid(valid);
}
state = (State)metaData.get(STATE);
Long cSeq = (Long) metaData.get(CSEQ);
if(cSeq != null) {
cseq = cSeq;
}
Boolean iwr = (Boolean) metaData.get(INVALIDATE_WHEN_READY);
if(iwr != null) {
invalidateWhenReady = iwr;
}
Boolean rti = (Boolean) metaData.get(READY_TO_INVALIDATE);
if(rti != null) {
readyToInvalidate = rti;
}
sessionCreatingDialogId = (String) metaData.get(DIALOG_ID);
proxy = (ProxyImpl) metaData.get(PROXY);
if(proxy != null) {
proxy.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
}
transport = (String) metaData.get(TRANSPORT);
Integer size = (Integer) metaData.get(B2B_SESSION_SIZE);
String[][] sessionArray = (String[][])metaData.get(B2B_SESSION_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua session array size = " + size + ", value = " + sessionArray);
}
if(size != null && sessionArray != null) {
Map<MobicentsSipSessionKey, MobicentsSipSessionKey> sessionMap = new ConcurrentHashMap<MobicentsSipSessionKey, MobicentsSipSessionKey>();
for (int i = 0; i < size; i++) {
String key = sessionArray[0][i];
String value = sessionArray[1][i];
try {
SipSessionKey sipSessionKeyKey = SessionManagerUtil.parseSipSessionKey(key);
SipSessionKey sipSessionKeyValue = SessionManagerUtil.parseSipSessionKey(value);
sessionMap.put(sipSessionKeyKey, sipSessionKeyValue);
} catch (ParseException e) {
logger.warn("couldn't parse a deserialized sip session key from the B2BUA", e);
}
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setSessionMap(sessionMap);
}
SipServletRequestImpl sessionRequest = (SipServletRequestImpl) metaData.get(SESSION_TX_REQUEST);
if(logger.isDebugEnabled()) {
logger.debug("session transaction creation request = " + sessionRequest);
}
if(sessionRequest != null) {
sessionCreatingTransactionRequest = sessionRequest;
}
Boolean isSessionStx = (Boolean) metaData.get(IS_SESSION_TX_REQUEST_SERVER);
if(logger.isDebugEnabled()) {
logger.debug("is session transaction creation server = " + isSessionStx);
}
if(isSessionStx != null) {
isSessionCreatingTransactionServer = isSessionCreatingTransactionServer;
}
if(((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).getReplicationStrategy() == ReplicationStrategy.EarlyDialog) {
Integer txsSize = (Integer) metaData.get(TXS_SIZE);
String[] txIds = (String[])metaData.get(TXS_IDS);
Boolean[] txTypes = (Boolean[])metaData.get(TXS_TYPE);
if(logger.isDebugEnabled()) {
logger.debug("tx array size = " + txsSize + ", value = " + txIds);
}
if(txsSize != null && txIds != null) {
for (int i = 0; i < txsSize; i++) {
String txId = txIds[i];
Boolean txType = txTypes[i];
if(logger.isDebugEnabled()) {
logger.debug("trying to find tx with id = " + txId + ", type = " + txType + " locally or in the distributed cache");
}
Transaction transaction = ((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).findTransaction(txId, txType);
addOngoingTransaction(transaction);
if(transaction != null) {
if(transaction instanceof ServerTransaction) {
acksReceived.put(((RequestExt)transaction.getRequest()).getCSeqHeader().getSeqNumber(), false);
} else if(proxy != null) {
final TransactionApplicationData transactionApplicationData = (TransactionApplicationData) transaction.getApplicationData();
if(logger.isDebugEnabled()) {
logger.debug("transaction application data from tx id " + txId + " is " + transactionApplicationData);
}
if(transactionApplicationData != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating proxy from the transaction application data");
}
proxy.getTransactionMap().put(txId, transactionApplicationData);
ProxyBranchImpl proxyBranchImpl = transactionApplicationData.getProxyBranch();
if(proxyBranchImpl != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating branch from the transaction application data");
}
proxyBranchImpl.setOutgoingRequest((SipServletRequestImpl)transactionApplicationData.getSipServletMessage());
proxyBranchImpl.setOriginalRequest((SipServletRequestImpl)proxy.getOriginalRequest());
proxyBranchImpl.setProxy(proxy);
proxy.addProxyBranch(proxyBranchImpl);
}
}
}
}
}
}
String toTag = (String) metaData.get(TO_TAG);
if(logger.isDebugEnabled()) {
logger.debug("sessionkey replicated totag to " + toTag);
}
if(key.getToTag() == null && toTag != null && toTag.trim().length() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("setting sessionkey totag to " + toTag);
}
key.setToTag(toTag, false);
}
// Fix for Issue 2739 : Null returned for B2BUAHelperImpl.getLinkedSipServletRequest() in Early Dailog Failover
size = (Integer) metaData.get(B2B_LINKED_REQUESTS_SIZE);
SipServletRequestImpl[][] linkedRequests = (SipServletRequestImpl[][])metaData.get(B2B_LINKED_REQUESTS_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua linked requests array size = " + size + ", value = " + linkedRequests);
}
if(size != null && linkedRequests != null) {
Map<SipServletRequestImpl, SipServletRequestImpl> linkedRequestsMap = new ConcurrentHashMap<SipServletRequestImpl, SipServletRequestImpl>();
for (int i = 0; i < size; i++) {
SipServletRequestImpl key = linkedRequests[0][i];
SipServletRequestImpl value = linkedRequests[1][i];
linkedRequestsMap.put(key, value);
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setOriginalRequestMap(linkedRequestsMap);
}
}
if(logger.isDebugEnabled()) {
logger.debug("dialog to inject " + sessionCreatingDialogId);
if(sessionCreatingDialogId != null) {
logger.debug("dialog id of the dialog to inject " + sessionCreatingDialogId);
}
}
if(sessionCreatingDialogId != null && sessionCreatingDialogId.length() > 0) {
Container context = getManager().getContainer();
Container container = context.getParent().getParent();
if(container instanceof Engine) {
Service service = ((Engine)container).getService();
if(service instanceof SipService) {
SipService sipService = (SipService) service;
SipStack sipStack = sipService.getSipStack();
if(sipStack != null) {
sessionCreatingDialog = ((ClusteredSipStack)sipStack).getDialog(sessionCreatingDialogId);
if(logger.isDebugEnabled()) {
logger.debug("dialog injected " + sessionCreatingDialog);
}
}
}
}
}
}
|
protected void updateSipSession(DistributableSipSessionMetadata md) {
//From SipSession
final Map<String, Object> metaData = md.getMetaData();
handlerServlet = (String) metaData.get(HANDLER);
Boolean valid = (Boolean)metaData.get(IS_VALID);
if(valid != null) {
// call to super very important to avoid setting the session dirty on reload and rewrite to the cache
super.setValid(valid);
}
state = (State)metaData.get(STATE);
if(logger.isDebugEnabled()) {
logger.debug("replicated sip session state = " + state);
}
// http://code.google.com/p/sipservlets/issues/detail?id=42
// in case of REGISTER (or out of dialog requests) , the state will have stayed INITIAL
// and as such not changed so not replicated, thus if state is null we default to INITIAL
if(state == null) {
state = State.INITIAL;
}
Long cSeq = (Long) metaData.get(CSEQ);
if(cSeq != null) {
cseq = cSeq;
}
Boolean iwr = (Boolean) metaData.get(INVALIDATE_WHEN_READY);
if(iwr != null) {
invalidateWhenReady = iwr;
}
Boolean rti = (Boolean) metaData.get(READY_TO_INVALIDATE);
if(rti != null) {
readyToInvalidate = rti;
}
sessionCreatingDialogId = (String) metaData.get(DIALOG_ID);
proxy = (ProxyImpl) metaData.get(PROXY);
if(proxy != null) {
proxy.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
}
transport = (String) metaData.get(TRANSPORT);
Integer size = (Integer) metaData.get(B2B_SESSION_SIZE);
String[][] sessionArray = (String[][])metaData.get(B2B_SESSION_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua session array size = " + size + ", value = " + sessionArray);
}
if(size != null && sessionArray != null) {
Map<MobicentsSipSessionKey, MobicentsSipSessionKey> sessionMap = new ConcurrentHashMap<MobicentsSipSessionKey, MobicentsSipSessionKey>();
for (int i = 0; i < size; i++) {
String key = sessionArray[0][i];
String value = sessionArray[1][i];
try {
SipSessionKey sipSessionKeyKey = SessionManagerUtil.parseSipSessionKey(key);
SipSessionKey sipSessionKeyValue = SessionManagerUtil.parseSipSessionKey(value);
sessionMap.put(sipSessionKeyKey, sipSessionKeyValue);
} catch (ParseException e) {
logger.warn("couldn't parse a deserialized sip session key from the B2BUA", e);
}
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setSessionMap(sessionMap);
}
SipServletRequestImpl sessionRequest = (SipServletRequestImpl) metaData.get(SESSION_TX_REQUEST);
if(logger.isDebugEnabled()) {
logger.debug("session transaction creation request = " + sessionRequest);
}
if(sessionRequest != null) {
sessionCreatingTransactionRequest = sessionRequest;
}
Boolean isSessionStx = (Boolean) metaData.get(IS_SESSION_TX_REQUEST_SERVER);
if(logger.isDebugEnabled()) {
logger.debug("is session transaction creation server = " + isSessionStx);
}
if(isSessionStx != null) {
isSessionCreatingTransactionServer = isSessionCreatingTransactionServer;
}
if(((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).getReplicationStrategy() == ReplicationStrategy.EarlyDialog) {
Integer txsSize = (Integer) metaData.get(TXS_SIZE);
String[] txIds = (String[])metaData.get(TXS_IDS);
Boolean[] txTypes = (Boolean[])metaData.get(TXS_TYPE);
if(logger.isDebugEnabled()) {
logger.debug("tx array size = " + txsSize + ", value = " + txIds);
}
if(txsSize != null && txIds != null) {
for (int i = 0; i < txsSize; i++) {
String txId = txIds[i];
Boolean txType = txTypes[i];
if(logger.isDebugEnabled()) {
logger.debug("trying to find tx with id = " + txId + ", type = " + txType + " locally or in the distributed cache");
}
Transaction transaction = ((ClusteredSipStack)StaticServiceHolder.sipStandardService.getSipStack()).findTransaction(txId, txType);
addOngoingTransaction(transaction);
if(transaction != null) {
if(transaction instanceof ServerTransaction) {
acksReceived.put(((RequestExt)transaction.getRequest()).getCSeqHeader().getSeqNumber(), false);
} else if(proxy != null) {
final TransactionApplicationData transactionApplicationData = (TransactionApplicationData) transaction.getApplicationData();
if(logger.isDebugEnabled()) {
logger.debug("transaction application data from tx id " + txId + " is " + transactionApplicationData);
}
if(transactionApplicationData != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating proxy from the transaction application data");
}
proxy.getTransactionMap().put(txId, transactionApplicationData);
ProxyBranchImpl proxyBranchImpl = transactionApplicationData.getProxyBranch();
if(proxyBranchImpl != null) {
if(logger.isDebugEnabled()) {
logger.debug("populating branch from the transaction application data");
}
proxyBranchImpl.setOutgoingRequest((SipServletRequestImpl)transactionApplicationData.getSipServletMessage());
proxyBranchImpl.setOriginalRequest((SipServletRequestImpl)proxy.getOriginalRequest());
proxyBranchImpl.setProxy(proxy);
proxy.addProxyBranch(proxyBranchImpl);
}
}
}
}
}
}
String toTag = (String) metaData.get(TO_TAG);
if(logger.isDebugEnabled()) {
logger.debug("sessionkey replicated totag to " + toTag);
}
if(key.getToTag() == null && toTag != null && toTag.trim().length() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("setting sessionkey totag to " + toTag);
}
key.setToTag(toTag, false);
}
// Fix for Issue 2739 : Null returned for B2BUAHelperImpl.getLinkedSipServletRequest() in Early Dailog Failover
size = (Integer) metaData.get(B2B_LINKED_REQUESTS_SIZE);
SipServletRequestImpl[][] linkedRequests = (SipServletRequestImpl[][])metaData.get(B2B_LINKED_REQUESTS_MAP);
if(logger.isDebugEnabled()) {
logger.debug("b2bua linked requests array size = " + size + ", value = " + linkedRequests);
}
if(size != null && linkedRequests != null) {
Map<SipServletRequestImpl, SipServletRequestImpl> linkedRequestsMap = new ConcurrentHashMap<SipServletRequestImpl, SipServletRequestImpl>();
for (int i = 0; i < size; i++) {
SipServletRequestImpl key = linkedRequests[0][i];
SipServletRequestImpl value = linkedRequests[1][i];
linkedRequestsMap.put(key, value);
}
if(b2buaHelper == null) {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setMobicentsSipFactory(getManager().getMobicentsSipFactory());
b2buaHelper.setSipManager(getManager());
}
b2buaHelper.setOriginalRequestMap(linkedRequestsMap);
}
}
if(logger.isDebugEnabled()) {
logger.debug("dialog to inject " + sessionCreatingDialogId);
if(sessionCreatingDialogId != null) {
logger.debug("dialog id of the dialog to inject " + sessionCreatingDialogId);
}
}
if(sessionCreatingDialogId != null && sessionCreatingDialogId.length() > 0) {
Container context = getManager().getContainer();
Container container = context.getParent().getParent();
if(container instanceof Engine) {
Service service = ((Engine)container).getService();
if(service instanceof SipService) {
SipService sipService = (SipService) service;
SipStack sipStack = sipService.getSipStack();
if(sipStack != null) {
sessionCreatingDialog = ((ClusteredSipStack)sipStack).getDialog(sessionCreatingDialogId);
if(logger.isDebugEnabled()) {
logger.debug("dialog injected " + sessionCreatingDialog);
}
}
}
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AllTests.java
index 3a375ee05..a2426991d 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AllTests.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AllTests.java
@@ -1,31 +1,33 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.reconciler.dropins;
import junit.framework.*;
/**
* To run the reconciler tests, you must perform some manual setup steps:
* 1) Download the platform runtime binary zip (latest build or the one you want to test).
* 2) Set the following system property to the file system path of the binary zip. For example:
*
* -Dorg.eclipse.equinox.p2.reconciler.tests.platform.archive=c:/tmp/eclipse-platform-3.4-win32.zip
*/
public class AllTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BasicTests.suite());
suite.addTest(ConfigurationTests.suite());
suite.addTest(FeaturePatchTest.suite());
- suite.addTest(SharedInstallTests.suite());
+ // disabled for now... seeing a lot of chmod errors in the console on the test machines
+ // and trying to lower down the cause.
+ //suite.addTest(SharedInstallTests.suite());
return suite;
}
}
| true | true |
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BasicTests.suite());
suite.addTest(ConfigurationTests.suite());
suite.addTest(FeaturePatchTest.suite());
suite.addTest(SharedInstallTests.suite());
return suite;
}
|
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BasicTests.suite());
suite.addTest(ConfigurationTests.suite());
suite.addTest(FeaturePatchTest.suite());
// disabled for now... seeing a lot of chmod errors in the console on the test machines
// and trying to lower down the cause.
//suite.addTest(SharedInstallTests.suite());
return suite;
}
|
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/DatasourceStep2.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/DatasourceStep2.java
index d1ab4979..a2e47012 100644
--- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/DatasourceStep2.java
+++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/DatasourceStep2.java
@@ -1,236 +1,236 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.shared.subsys.jca.wizard;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SingleSelectionModel;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.shared.subsys.jca.model.DataSource;
import org.jboss.as.console.client.shared.subsys.jca.model.JDBCDriver;
import org.jboss.as.console.client.widgets.ComboBox;
import org.jboss.as.console.client.widgets.DefaultPager;
import org.jboss.as.console.client.widgets.DialogueOptions;
import org.jboss.as.console.client.widgets.tables.DefaultCellTable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Heiko Braun
* @date 4/18/11
*/
public class DatasourceStep2 {
private NewDatasourceWizard wizard;
private DataSource editedEntity;
private SingleSelectionModel<JDBCDriver> selectionModel;
private CellTable<JDBCDriver> table;
private ComboBox groupSelection;
private boolean isStandalone;
public DatasourceStep2(NewDatasourceWizard wizard) {
this.wizard = wizard;
this.isStandalone = wizard.getBootstrap().isStandalone();
}
Widget asWidget() {
VerticalPanel layout = new VerticalPanel();
layout.getElement().setAttribute("style", "margin:10px; vertical-align:center;width:95%");
layout.add(new HTML("<h3>Step 2/3: JDBC Driver</h3>Please chose one of the available drivers."));
- if(isStandalone)
+ if(!isStandalone)
{
groupSelection = new ComboBox();
Set<String> groupNames = new HashSet<String>(wizard.getDrivers().size());
for(JDBCDriver driver : wizard.getDrivers())
groupNames.add(driver.getGroup());
groupSelection.setValues(groupNames);
groupSelection.setItemSelected(0, true);
HorizontalPanel horz = new HorizontalPanel();
horz.setStyleName("fill-layout-width");
Label label = new HTML("Server Group"+": ");
label.setStyleName("form-item-title");
horz.add(label);
Widget selector = groupSelection.asWidget();
horz.add(selector);
label.getElement().getParentElement().setAttribute("align", "right");
selector.getElement().getParentElement().setAttribute("width", "100%");
layout.add(horz);
groupSelection.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
filterTable(event.getValue(), getTable());
}
});
}
// ---
table = new DefaultCellTable<JDBCDriver>(5);
TextColumn<JDBCDriver> nameColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getName();
}
};
TextColumn<JDBCDriver> groupColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getGroup();
}
};
table.addColumn(nameColumn, "Name");
if(!isStandalone)
table.addColumn(groupColumn, "Server Group");
selectionModel = new SingleSelectionModel<JDBCDriver>();
table.setSelectionModel(selectionModel);
// filter and select first record
if(isStandalone)
provisionTable(table);
else
filterTable(groupSelection.getSelectedValue(), table);
layout.add(table);
DefaultPager pager = new DefaultPager();
pager.setDisplay(table);
layout.add(pager);
// ----
ClickHandler submitHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SingleSelectionModel<JDBCDriver> selection =
(SingleSelectionModel<JDBCDriver>) table.getSelectionModel();
JDBCDriver driver = selection.getSelectedObject();
if(driver!=null) { // force selected driver
editedEntity.setDriverName(driver.getName());
editedEntity.setDriverClass(driver.getDriverClass());
editedEntity.setMajorVersion(driver.getMajorVersion());
editedEntity.setMinorVersion(driver.getMinorVersion());
wizard.onConfigureDriver(editedEntity);
}
else {
Window.alert("Please select a driver!");
}
}
};
ClickHandler cancelHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
wizard.getPresenter().closeDialogue();
}
};
DialogueOptions options = new DialogueOptions(
"Next ››",submitHandler,
"cancel",cancelHandler
);
layout.add(options);
return layout;
}
private void provisionTable(CellTable<JDBCDriver> table) {
List<JDBCDriver> drivers = wizard.getDrivers();
table.setRowCount(drivers.size(), true);
table.setRowData(drivers);
// clear selection
JDBCDriver selectedDriver = selectionModel.getSelectedObject();
if(selectedDriver!=null)
selectionModel.setSelected(selectedDriver, false);
// new default selection
if(drivers.size()>0) {
selectionModel.setSelected(drivers.get(0), true);
}
}
private void filterTable(String group, CellTable<JDBCDriver> table) {
List<JDBCDriver> drivers = wizard.getDrivers();
List<JDBCDriver> filtered = new ArrayList<JDBCDriver>();
for(JDBCDriver candidate : drivers)
{
if(group.equals(candidate.getGroup()))
filtered.add(candidate);
}
table.setRowCount(filtered.size(), true);
table.setRowData(filtered);
// clear selection
JDBCDriver selectedDriver = selectionModel.getSelectedObject();
if(selectedDriver!=null)
selectionModel.setSelected(selectedDriver, false);
// new default selection
if(filtered.size()>0) {
selectionModel.setSelected(filtered.get(0), true);
}
}
void edit(DataSource entity)
{
this.editedEntity = entity;
}
private CellTable<JDBCDriver> getTable() {
return table;
}
}
| true | true |
Widget asWidget() {
VerticalPanel layout = new VerticalPanel();
layout.getElement().setAttribute("style", "margin:10px; vertical-align:center;width:95%");
layout.add(new HTML("<h3>Step 2/3: JDBC Driver</h3>Please chose one of the available drivers."));
if(isStandalone)
{
groupSelection = new ComboBox();
Set<String> groupNames = new HashSet<String>(wizard.getDrivers().size());
for(JDBCDriver driver : wizard.getDrivers())
groupNames.add(driver.getGroup());
groupSelection.setValues(groupNames);
groupSelection.setItemSelected(0, true);
HorizontalPanel horz = new HorizontalPanel();
horz.setStyleName("fill-layout-width");
Label label = new HTML("Server Group"+": ");
label.setStyleName("form-item-title");
horz.add(label);
Widget selector = groupSelection.asWidget();
horz.add(selector);
label.getElement().getParentElement().setAttribute("align", "right");
selector.getElement().getParentElement().setAttribute("width", "100%");
layout.add(horz);
groupSelection.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
filterTable(event.getValue(), getTable());
}
});
}
// ---
table = new DefaultCellTable<JDBCDriver>(5);
TextColumn<JDBCDriver> nameColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getName();
}
};
TextColumn<JDBCDriver> groupColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getGroup();
}
};
table.addColumn(nameColumn, "Name");
if(!isStandalone)
table.addColumn(groupColumn, "Server Group");
selectionModel = new SingleSelectionModel<JDBCDriver>();
table.setSelectionModel(selectionModel);
// filter and select first record
if(isStandalone)
provisionTable(table);
else
filterTable(groupSelection.getSelectedValue(), table);
layout.add(table);
DefaultPager pager = new DefaultPager();
pager.setDisplay(table);
layout.add(pager);
// ----
ClickHandler submitHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SingleSelectionModel<JDBCDriver> selection =
(SingleSelectionModel<JDBCDriver>) table.getSelectionModel();
JDBCDriver driver = selection.getSelectedObject();
if(driver!=null) { // force selected driver
editedEntity.setDriverName(driver.getName());
editedEntity.setDriverClass(driver.getDriverClass());
editedEntity.setMajorVersion(driver.getMajorVersion());
editedEntity.setMinorVersion(driver.getMinorVersion());
wizard.onConfigureDriver(editedEntity);
}
else {
Window.alert("Please select a driver!");
}
}
};
ClickHandler cancelHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
wizard.getPresenter().closeDialogue();
}
};
DialogueOptions options = new DialogueOptions(
"Next ››",submitHandler,
"cancel",cancelHandler
);
layout.add(options);
return layout;
}
|
Widget asWidget() {
VerticalPanel layout = new VerticalPanel();
layout.getElement().setAttribute("style", "margin:10px; vertical-align:center;width:95%");
layout.add(new HTML("<h3>Step 2/3: JDBC Driver</h3>Please chose one of the available drivers."));
if(!isStandalone)
{
groupSelection = new ComboBox();
Set<String> groupNames = new HashSet<String>(wizard.getDrivers().size());
for(JDBCDriver driver : wizard.getDrivers())
groupNames.add(driver.getGroup());
groupSelection.setValues(groupNames);
groupSelection.setItemSelected(0, true);
HorizontalPanel horz = new HorizontalPanel();
horz.setStyleName("fill-layout-width");
Label label = new HTML("Server Group"+": ");
label.setStyleName("form-item-title");
horz.add(label);
Widget selector = groupSelection.asWidget();
horz.add(selector);
label.getElement().getParentElement().setAttribute("align", "right");
selector.getElement().getParentElement().setAttribute("width", "100%");
layout.add(horz);
groupSelection.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
filterTable(event.getValue(), getTable());
}
});
}
// ---
table = new DefaultCellTable<JDBCDriver>(5);
TextColumn<JDBCDriver> nameColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getName();
}
};
TextColumn<JDBCDriver> groupColumn = new TextColumn<JDBCDriver>() {
@Override
public String getValue(JDBCDriver record) {
return record.getGroup();
}
};
table.addColumn(nameColumn, "Name");
if(!isStandalone)
table.addColumn(groupColumn, "Server Group");
selectionModel = new SingleSelectionModel<JDBCDriver>();
table.setSelectionModel(selectionModel);
// filter and select first record
if(isStandalone)
provisionTable(table);
else
filterTable(groupSelection.getSelectedValue(), table);
layout.add(table);
DefaultPager pager = new DefaultPager();
pager.setDisplay(table);
layout.add(pager);
// ----
ClickHandler submitHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SingleSelectionModel<JDBCDriver> selection =
(SingleSelectionModel<JDBCDriver>) table.getSelectionModel();
JDBCDriver driver = selection.getSelectedObject();
if(driver!=null) { // force selected driver
editedEntity.setDriverName(driver.getName());
editedEntity.setDriverClass(driver.getDriverClass());
editedEntity.setMajorVersion(driver.getMajorVersion());
editedEntity.setMinorVersion(driver.getMinorVersion());
wizard.onConfigureDriver(editedEntity);
}
else {
Window.alert("Please select a driver!");
}
}
};
ClickHandler cancelHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
wizard.getPresenter().closeDialogue();
}
};
DialogueOptions options = new DialogueOptions(
"Next ››",submitHandler,
"cancel",cancelHandler
);
layout.add(options);
return layout;
}
|
diff --git a/src/org/apache/xpath/patterns/NodeTest.java b/src/org/apache/xpath/patterns/NodeTest.java
index 1407d15b..2a13ad84 100644
--- a/src/org/apache/xpath/patterns/NodeTest.java
+++ b/src/org/apache/xpath/patterns/NodeTest.java
@@ -1,236 +1,238 @@
package org.apache.xpath.patterns;
import org.w3c.dom.traversal.NodeFilter;
import org.apache.xpath.compiler.OpCodes;
import org.apache.xpath.XPath;
import org.apache.xpath.DOMHelper;
import org.apache.xpath.Expression;
import org.apache.xpath.XPathContext;
import org.apache.xpath.objects.XNumber;
import org.apache.xpath.objects.XObject;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeFilter;
public class NodeTest extends Expression
{
public static final String WILD = "*";
/**
* This attribute determines which node types are accepted.
*/
private int m_whatToShow;
public static final int SHOW_NAMESPACE = 0x00001000;
/**
* This attribute determines which node types are accepted.
* These constants are defined in the <code>NodeFilter</code>
* interface.
*/
public int getWhatToShow()
{
return m_whatToShow;
}
String m_namespace;
String m_name;
XNumber m_score;
static final XNumber SCORE_NODETEST
= new XNumber( XPath.MATCH_SCORE_NODETEST );
static final XNumber SCORE_NSWILD
= new XNumber( XPath.MATCH_SCORE_NSWILD );
static final XNumber SCORE_QNAME
= new XNumber( XPath.MATCH_SCORE_QNAME );
static final XNumber SCORE_OTHER
= new XNumber( XPath.MATCH_SCORE_OTHER );
public static final XNumber SCORE_NONE
= new XNumber( XPath.MATCH_SCORE_NONE );
public NodeTest(int whatToShow, String namespace, String name)
{
initNodeTest(whatToShow, namespace, name);
}
public NodeTest(int whatToShow)
{
initNodeTest(whatToShow);
}
public NodeTest()
{
}
public void initNodeTest(int whatToShow)
{
m_whatToShow = whatToShow;
calcScore();
}
public void initNodeTest(int whatToShow, String namespace, String name)
{
m_whatToShow = whatToShow;
m_namespace = namespace;
m_name = name;
calcScore();
}
/**
* Static calc of match score.
*/
private final void calcScore()
{
if((m_namespace == null) && (m_name == null))
m_score = SCORE_NODETEST;
else if(((m_namespace == WILD) || (m_namespace == null)) && (m_name == WILD))
m_score = SCORE_NODETEST;
else if((m_namespace != WILD) && (m_name == WILD))
m_score = SCORE_NSWILD;
else
m_score = SCORE_QNAME;
}
public static void debugWhatToShow(int whatToShow)
{
java.util.Vector v = new java.util.Vector();
if(0 != (whatToShow & NodeFilter.SHOW_ATTRIBUTE))
v.addElement("SHOW_ATTRIBUTE");
if(0 != (whatToShow & NodeFilter.SHOW_CDATA_SECTION))
v.addElement("SHOW_CDATA_SECTION");
if(0 != (whatToShow & NodeFilter.SHOW_COMMENT))
v.addElement("SHOW_COMMENT");
if(0 != (whatToShow & NodeFilter.SHOW_DOCUMENT))
v.addElement("SHOW_DOCUMENT");
if(0 != (whatToShow & NodeFilter.SHOW_DOCUMENT_FRAGMENT))
v.addElement("SHOW_DOCUMENT_FRAGMENT");
if(0 != (whatToShow & NodeFilter.SHOW_DOCUMENT_TYPE))
v.addElement("SHOW_DOCUMENT_TYPE");
if(0 != (whatToShow & NodeFilter.SHOW_ELEMENT))
v.addElement("SHOW_ELEMENT");
if(0 != (whatToShow & NodeFilter.SHOW_ENTITY))
v.addElement("SHOW_ENTITY");
if(0 != (whatToShow & NodeFilter.SHOW_ENTITY_REFERENCE))
v.addElement("SHOW_ENTITY_REFERENCE");
if(0 != (whatToShow & NodeFilter.SHOW_NOTATION))
v.addElement("SHOW_NOTATION");
if(0 != (whatToShow & NodeFilter.SHOW_PROCESSING_INSTRUCTION))
v.addElement("SHOW_PROCESSING_INSTRUCTION");
if(0 != (whatToShow & NodeFilter.SHOW_TEXT))
v.addElement("SHOW_TEXT");
int n = v.size();
for(int i = 0; i < n; i++)
{
if(i > 0)
System.out.print(" | ");
System.out.print(v.elementAt(i));
}
if(0 == n)
System.out.print("empty whatToShow: "+whatToShow);
System.out.println();
}
/**
* Test a node to see if it matches the given node test.
* @param xpath The xpath that is executing.
* @param context The current source tree context node.
* @param opPos The current position in the xpath.m_opMap array.
* @param len The length of the argument.
* @param len The type of the step.
* @returns score in an XNumber, one of MATCH_SCORE_NODETEST,
* MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
*/
public XObject execute(XPathContext xctxt)
throws org.xml.sax.SAXException
{
Node context = xctxt.getCurrentNode();
int nodeType = context.getNodeType();
int whatToShow = getWhatToShow();
// debugWhatToShow(whatToShow);
if(whatToShow == NodeFilter.SHOW_ALL)
return m_score;
int nodeBit = (whatToShow & (0x00000001 << (nodeType-1)));
switch(nodeBit)
{
case NodeFilter.SHOW_DOCUMENT:
case NodeFilter.SHOW_COMMENT:
return m_score;
case NodeFilter.SHOW_CDATA_SECTION:
case NodeFilter.SHOW_TEXT:
return (!xctxt.getDOMHelper().shouldStripSourceNode(context))
? m_score : SCORE_NONE;
case NodeFilter.SHOW_PROCESSING_INSTRUCTION:
return subPartMatch(context.getNodeName(), m_name)
? m_score : SCORE_NONE;
// From the draft: "Two expanded names are equal if they
// have the same local part, and either both have no URI or
// both have the same URI."
// "A node test * is true for any node of the principal node type.
// For example, child::* will select all element children of the
// context node, and attribute::* will select all attributes of
// the context node."
// "A node test can have the form NCName:*. In this case, the prefix
// is expanded in the same way as with a QName using the context
// namespace declarations. The node test will be true for any node
// of the principal type whose expanded name has the URI to which
// the prefix expands, regardless of the local part of the name."
case NodeFilter.SHOW_ATTRIBUTE:
{
DOMHelper dh = xctxt.getDOMHelper();
int isNamespace = (whatToShow & SHOW_NAMESPACE);
if(0 == isNamespace)
{
if(!dh.isNamespaceNode(context))
- return (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
- && subPartMatch(dh.getLocalNameOfNode(context), m_name)) ?
+ return ((m_name == WILD) ||
+ (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
+ && subPartMatch(dh.getLocalNameOfNode(context), m_name))) ?
m_score : SCORE_NONE;
else
return SCORE_NONE;
}
else
{
if(dh.isNamespaceNode(context))
{
String ns = context.getNodeValue();
return (subPartMatch(ns, m_name)) ?
m_score : SCORE_NONE;
}
else
return SCORE_NONE;
}
}
case NodeFilter.SHOW_ELEMENT:
{
DOMHelper dh = xctxt.getDOMHelper();
- return (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
- && subPartMatch(dh.getLocalNameOfNode(context), m_name)) ?
+ return ((m_name == WILD) ||
+ (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
+ && subPartMatch(dh.getLocalNameOfNode(context), m_name))) ?
m_score : SCORE_NONE;
}
default:
return SCORE_NONE;
} // end switch(testType)
}
/**
* Two names are equal if they and either both are null or
* the name t is wild and the name p is non-null, or the two
* strings are equal.
*/
private boolean subPartMatch(String p, String t)
{
// boolean b = (p == t) || ((null != p) && ((t == WILD) || p.equals(t)));
// System.out.println("subPartMatch - p: "+p+", t: "+t+", result: "+b);
return (p == t) || ((null != p) && ((t == WILD) || p.equals(t)));
}
}
| false | true |
public XObject execute(XPathContext xctxt)
throws org.xml.sax.SAXException
{
Node context = xctxt.getCurrentNode();
int nodeType = context.getNodeType();
int whatToShow = getWhatToShow();
// debugWhatToShow(whatToShow);
if(whatToShow == NodeFilter.SHOW_ALL)
return m_score;
int nodeBit = (whatToShow & (0x00000001 << (nodeType-1)));
switch(nodeBit)
{
case NodeFilter.SHOW_DOCUMENT:
case NodeFilter.SHOW_COMMENT:
return m_score;
case NodeFilter.SHOW_CDATA_SECTION:
case NodeFilter.SHOW_TEXT:
return (!xctxt.getDOMHelper().shouldStripSourceNode(context))
? m_score : SCORE_NONE;
case NodeFilter.SHOW_PROCESSING_INSTRUCTION:
return subPartMatch(context.getNodeName(), m_name)
? m_score : SCORE_NONE;
// From the draft: "Two expanded names are equal if they
// have the same local part, and either both have no URI or
// both have the same URI."
// "A node test * is true for any node of the principal node type.
// For example, child::* will select all element children of the
// context node, and attribute::* will select all attributes of
// the context node."
// "A node test can have the form NCName:*. In this case, the prefix
// is expanded in the same way as with a QName using the context
// namespace declarations. The node test will be true for any node
// of the principal type whose expanded name has the URI to which
// the prefix expands, regardless of the local part of the name."
case NodeFilter.SHOW_ATTRIBUTE:
{
DOMHelper dh = xctxt.getDOMHelper();
int isNamespace = (whatToShow & SHOW_NAMESPACE);
if(0 == isNamespace)
{
if(!dh.isNamespaceNode(context))
return (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
&& subPartMatch(dh.getLocalNameOfNode(context), m_name)) ?
m_score : SCORE_NONE;
else
return SCORE_NONE;
}
else
{
if(dh.isNamespaceNode(context))
{
String ns = context.getNodeValue();
return (subPartMatch(ns, m_name)) ?
m_score : SCORE_NONE;
}
else
return SCORE_NONE;
}
}
case NodeFilter.SHOW_ELEMENT:
{
DOMHelper dh = xctxt.getDOMHelper();
return (subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
&& subPartMatch(dh.getLocalNameOfNode(context), m_name)) ?
m_score : SCORE_NONE;
}
default:
return SCORE_NONE;
} // end switch(testType)
}
|
public XObject execute(XPathContext xctxt)
throws org.xml.sax.SAXException
{
Node context = xctxt.getCurrentNode();
int nodeType = context.getNodeType();
int whatToShow = getWhatToShow();
// debugWhatToShow(whatToShow);
if(whatToShow == NodeFilter.SHOW_ALL)
return m_score;
int nodeBit = (whatToShow & (0x00000001 << (nodeType-1)));
switch(nodeBit)
{
case NodeFilter.SHOW_DOCUMENT:
case NodeFilter.SHOW_COMMENT:
return m_score;
case NodeFilter.SHOW_CDATA_SECTION:
case NodeFilter.SHOW_TEXT:
return (!xctxt.getDOMHelper().shouldStripSourceNode(context))
? m_score : SCORE_NONE;
case NodeFilter.SHOW_PROCESSING_INSTRUCTION:
return subPartMatch(context.getNodeName(), m_name)
? m_score : SCORE_NONE;
// From the draft: "Two expanded names are equal if they
// have the same local part, and either both have no URI or
// both have the same URI."
// "A node test * is true for any node of the principal node type.
// For example, child::* will select all element children of the
// context node, and attribute::* will select all attributes of
// the context node."
// "A node test can have the form NCName:*. In this case, the prefix
// is expanded in the same way as with a QName using the context
// namespace declarations. The node test will be true for any node
// of the principal type whose expanded name has the URI to which
// the prefix expands, regardless of the local part of the name."
case NodeFilter.SHOW_ATTRIBUTE:
{
DOMHelper dh = xctxt.getDOMHelper();
int isNamespace = (whatToShow & SHOW_NAMESPACE);
if(0 == isNamespace)
{
if(!dh.isNamespaceNode(context))
return ((m_name == WILD) ||
(subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
&& subPartMatch(dh.getLocalNameOfNode(context), m_name))) ?
m_score : SCORE_NONE;
else
return SCORE_NONE;
}
else
{
if(dh.isNamespaceNode(context))
{
String ns = context.getNodeValue();
return (subPartMatch(ns, m_name)) ?
m_score : SCORE_NONE;
}
else
return SCORE_NONE;
}
}
case NodeFilter.SHOW_ELEMENT:
{
DOMHelper dh = xctxt.getDOMHelper();
return ((m_name == WILD) ||
(subPartMatch(dh.getNamespaceOfNode(context), m_namespace)
&& subPartMatch(dh.getLocalNameOfNode(context), m_name))) ?
m_score : SCORE_NONE;
}
default:
return SCORE_NONE;
} // end switch(testType)
}
|
diff --git a/src/vues/VueToboggan.java b/src/vues/VueToboggan.java
index 428379d..6fc5490 100644
--- a/src/vues/VueToboggan.java
+++ b/src/vues/VueToboggan.java
@@ -1,98 +1,98 @@
package vues;
import ihm.ImagesManager;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import noyau.Aeroport;
import noyau.Toboggan;
import noyau.Aeroport.Mode;
public class VueToboggan extends Vue {
private Toboggan toboggan;
//TODO : set from xml
static private int tailleReelle = 2;
/**
* Constructeur de la VueToboggan
* @param vueGenerale
* @param image
* @param imageSel
* @param toboggan
*/
public VueToboggan(VueGenerale vueGenerale, ImagesManager imagesManager, Toboggan toboggan) {
super(vueGenerale, imagesManager);
this.toboggan = toboggan;
this.imageWidth = (int)Math.round(tailleReelle*vueGenerale.getEchelle());
this.imageHeight = (int)Math.round(tailleReelle*vueGenerale.getEchelle());
posPixel = new Point((int)Math.round(this.toboggan.getCoordonnees().x * this.vueGenerale.getEchelle() - imageWidth/2)
, (int)Math.round(this.toboggan.getCoordonnees().y * this.vueGenerale.getEchelle() - imageHeight/2));
rectangle = new Rectangle(posPixel.x, posPixel.y, imageWidth, imageHeight);
}
@Override
void dessin(Graphics g){
Graphics2D g2d = (Graphics2D)g;
if(selection){
g2d.drawImage(imagesManager.getImgTobogganSel(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
else{
g2d.drawImage(imagesManager.getImgToboggan(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
if(toboggan.getId() < 10){
Font f = new Font("Courier", Font.BOLD, imageWidth);
g2d.setFont(f);
g2d.setColor(Color.WHITE);
- g2d.drawString(Integer.toString(toboggan.getNoeud().getId()), (float)(posPixel.x + imageWidth/4), (float)(posPixel.y + imageHeight/1.25));
+ g2d.drawString(Integer.toString(toboggan.getId()), (float)(posPixel.x + imageWidth/4), (float)(posPixel.y + imageHeight/1.25));
}
else{
Font f = new Font("Courier", Font.BOLD, (int)Math.round(imageWidth/1.5));
g2d.setFont(f);
g2d.setColor(Color.WHITE);
- g2d.drawString(Integer.toString(toboggan.getNoeud().getId()), (float)(posPixel.x + imageWidth/6), (float)(posPixel.y + imageHeight/1.5));
+ g2d.drawString(Integer.toString(toboggan.getId()), (float)(posPixel.x + imageWidth/6), (float)(posPixel.y + imageHeight/1.5));
}
}
@Override
void action() {
this.selectionner();
vueGenerale.setChariotCourant(null);
vueGenerale.setTobogganCourant(this);
if(vueGenerale.getGuichetCourant() != null){
vueGenerale.getGuichetCourant().selectionner();
vueGenerale.getZoneInfo().setText("Pour ajouter un bagage cliquez sur Valider");
vueGenerale.getBandeauAjoutBagages().setNumeros(vueGenerale.getGuichetCourant().getGuichet().getId(),
vueGenerale.getTobogganCourant().getToboggan().getId());
vueGenerale.getBandeauAjoutBagages().setVisible(true);
}
else{
vueGenerale.getZoneInfo().setText("Veuillez selectionner un Guichet");
}
}
@Override
boolean clic(int x, int y) {
if(Aeroport.getMode() == Mode.MANUEL){
Point p = new Point(x, y);
return dansRectangle(p);
}
else{
return false;
}
}
public Toboggan getToboggan() {
return toboggan;
}
}
| false | true |
void dessin(Graphics g){
Graphics2D g2d = (Graphics2D)g;
if(selection){
g2d.drawImage(imagesManager.getImgTobogganSel(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
else{
g2d.drawImage(imagesManager.getImgToboggan(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
if(toboggan.getId() < 10){
Font f = new Font("Courier", Font.BOLD, imageWidth);
g2d.setFont(f);
g2d.setColor(Color.WHITE);
g2d.drawString(Integer.toString(toboggan.getNoeud().getId()), (float)(posPixel.x + imageWidth/4), (float)(posPixel.y + imageHeight/1.25));
}
else{
Font f = new Font("Courier", Font.BOLD, (int)Math.round(imageWidth/1.5));
g2d.setFont(f);
g2d.setColor(Color.WHITE);
g2d.drawString(Integer.toString(toboggan.getNoeud().getId()), (float)(posPixel.x + imageWidth/6), (float)(posPixel.y + imageHeight/1.5));
}
}
|
void dessin(Graphics g){
Graphics2D g2d = (Graphics2D)g;
if(selection){
g2d.drawImage(imagesManager.getImgTobogganSel(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
else{
g2d.drawImage(imagesManager.getImgToboggan(), posPixel.x, posPixel.y, imageWidth, imageHeight, vueGenerale);
}
if(toboggan.getId() < 10){
Font f = new Font("Courier", Font.BOLD, imageWidth);
g2d.setFont(f);
g2d.setColor(Color.WHITE);
g2d.drawString(Integer.toString(toboggan.getId()), (float)(posPixel.x + imageWidth/4), (float)(posPixel.y + imageHeight/1.25));
}
else{
Font f = new Font("Courier", Font.BOLD, (int)Math.round(imageWidth/1.5));
g2d.setFont(f);
g2d.setColor(Color.WHITE);
g2d.drawString(Integer.toString(toboggan.getId()), (float)(posPixel.x + imageWidth/6), (float)(posPixel.y + imageHeight/1.5));
}
}
|
diff --git a/java/AP2DX/src/AP2DX/sensor/Program.java b/java/AP2DX/src/AP2DX/sensor/Program.java
index 03aa61e..770c7be 100644
--- a/java/AP2DX/src/AP2DX/sensor/Program.java
+++ b/java/AP2DX/src/AP2DX/sensor/Program.java
@@ -1,60 +1,60 @@
package AP2DX.sensor;
import java.util.ArrayList;
import AP2DX.AP2DXBase;
import AP2DX.AP2DXMessage;
import AP2DX.Message;
import AP2DX.Module;
import AP2DX.specializedMessages.*;
public class Program extends AP2DXBase {
/**
* Entrypoint of mapper
*/
public static void main (String[] args){
new Program();
}
/**
* constructor
*/
public Program()
{
super(Module.SENSOR); // explicitly calls base constructor
System.out.println(" Running Sensor... ");
}
@Override
protected void doOverride() {
}
@Override
public ArrayList<Message> componentLogic(Message msg)
{
ArrayList<Message> messageList = new ArrayList<Message>();
- if (!msg.getType().isAp2dxMessage)
+ if (!msg.getMsgType().isAp2dxMessage)
{
System.out.println("Unexpected message in ap2dx.sensor.Program, was not an AP2DX message type.");
return null;
}
- switch (msg.getType())
+ switch (msg.getMsgType())
{
case AP2DX_SENSOR_SONAR:
SonarSensorMessage sonarSensorMessage = new SonarSensorMessage((AP2DXMessage)msg, IAM, Module.REFLEX);
messageList.add(sonarSensorMessage);
break;
default:
- System.out.println("Unexpected message type in ap2dx.sensor.Program: " + msg.getType());
+ System.out.println("Unexpected message type in ap2dx.sensor.Program: " + msg.getMsgType());
}
return messageList;
}
}
| false | true |
public ArrayList<Message> componentLogic(Message msg)
{
ArrayList<Message> messageList = new ArrayList<Message>();
if (!msg.getType().isAp2dxMessage)
{
System.out.println("Unexpected message in ap2dx.sensor.Program, was not an AP2DX message type.");
return null;
}
switch (msg.getType())
{
case AP2DX_SENSOR_SONAR:
SonarSensorMessage sonarSensorMessage = new SonarSensorMessage((AP2DXMessage)msg, IAM, Module.REFLEX);
messageList.add(sonarSensorMessage);
break;
default:
System.out.println("Unexpected message type in ap2dx.sensor.Program: " + msg.getType());
}
return messageList;
}
|
public ArrayList<Message> componentLogic(Message msg)
{
ArrayList<Message> messageList = new ArrayList<Message>();
if (!msg.getMsgType().isAp2dxMessage)
{
System.out.println("Unexpected message in ap2dx.sensor.Program, was not an AP2DX message type.");
return null;
}
switch (msg.getMsgType())
{
case AP2DX_SENSOR_SONAR:
SonarSensorMessage sonarSensorMessage = new SonarSensorMessage((AP2DXMessage)msg, IAM, Module.REFLEX);
messageList.add(sonarSensorMessage);
break;
default:
System.out.println("Unexpected message type in ap2dx.sensor.Program: " + msg.getMsgType());
}
return messageList;
}
|
diff --git a/org.oobium.build/src/org/oobium/build/gen/DbGenerator.java b/org.oobium.build/src/org/oobium/build/gen/DbGenerator.java
index 7b093448..d30f988f 100644
--- a/org.oobium.build/src/org/oobium/build/gen/DbGenerator.java
+++ b/org.oobium.build/src/org/oobium/build/gen/DbGenerator.java
@@ -1,327 +1,327 @@
/*******************************************************************************
* Copyright (c) 2010 Oobium, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Jeremy Dowdall <[email protected]> - initial API and implementation
******************************************************************************/
package org.oobium.build.gen;
import static org.oobium.persist.migrate.defs.Column.BINARY;
import static org.oobium.persist.migrate.defs.Column.BOOLEAN;
import static org.oobium.persist.migrate.defs.Column.DATE;
import static org.oobium.persist.migrate.defs.Column.DATESTAMPS;
import static org.oobium.persist.migrate.defs.Column.DECIMAL;
import static org.oobium.persist.migrate.defs.Column.DOUBLE;
import static org.oobium.persist.migrate.defs.Column.FLOAT;
import static org.oobium.persist.migrate.defs.Column.INTEGER;
import static org.oobium.persist.migrate.defs.Column.LONG;
import static org.oobium.persist.migrate.defs.Column.STRING;
import static org.oobium.persist.migrate.defs.Column.TEXT;
import static org.oobium.persist.migrate.defs.Column.TIME;
import static org.oobium.persist.migrate.defs.Column.TIMESTAMP;
import static org.oobium.persist.migrate.defs.Column.TIMESTAMPS;
import static org.oobium.utils.StringUtils.columnName;
import static org.oobium.utils.StringUtils.varName;
import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.oobium.build.gen.migration.JoinTable;
import org.oobium.build.gen.migration.ModelTable;
import org.oobium.build.model.ModelDefinition;
import org.oobium.build.model.ModelRelation;
import org.oobium.build.util.SourceFile;
import org.oobium.persist.Binary;
import org.oobium.persist.Text;
import org.oobium.persist.migrate.AbstractMigration;
import org.oobium.persist.migrate.Options;
import org.oobium.persist.migrate.defs.Column;
import org.oobium.persist.migrate.defs.Index;
import org.oobium.persist.migrate.defs.Table;
import org.oobium.persist.migrate.defs.columns.ForeignKey;
import org.oobium.utils.literal;
public class DbGenerator {
private static final Map<String, String> migrationTypes;
static {
migrationTypes = new HashMap<String, String>();
migrationTypes.put(Binary.class.getCanonicalName(), BINARY);
migrationTypes.put(byte[].class.getCanonicalName(), BINARY);
migrationTypes.put(String.class.getCanonicalName(), STRING);
migrationTypes.put(Text.class.getCanonicalName(), TEXT);
migrationTypes.put(Integer.class.getCanonicalName(), INTEGER);
migrationTypes.put(int.class.getCanonicalName(), INTEGER);
migrationTypes.put(Float.class.getCanonicalName(), FLOAT);
migrationTypes.put(float.class.getCanonicalName(), FLOAT);
migrationTypes.put(Long.class.getCanonicalName(), LONG);
migrationTypes.put(long.class.getCanonicalName(), LONG);
migrationTypes.put(Boolean.class.getCanonicalName(), BOOLEAN);
migrationTypes.put(boolean.class.getCanonicalName(), BOOLEAN);
migrationTypes.put(Double.class.getCanonicalName(), DOUBLE);
migrationTypes.put(double.class.getCanonicalName(), DOUBLE);
migrationTypes.put(Date.class.getCanonicalName(), TIMESTAMP);
migrationTypes.put(java.sql.Date.class.getCanonicalName(), DATE);
migrationTypes.put(Time.class.getCanonicalName(), TIME);
migrationTypes.put(Timestamp.class.getCanonicalName(), TIMESTAMP);
migrationTypes.put(BigDecimal.class.getCanonicalName(), DECIMAL);
}
public static String generate(String moduleName, ModelDefinition[] models) {
return new DbGenerator(moduleName, models).generate().getSource();
}
/**
* convert a Java type into a method
*/
private static final String getMethod(String javaType) {
String type = migrationTypes.get(javaType);
if(type != null) {
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
return "String";
}
private final String packageName;
private final String simpleName;
private ModelDefinition[] models;
private String source;
public DbGenerator(String moduleName, ModelDefinition[] models) {
this.packageName = moduleName.replace(File.separatorChar, '.') + ".migrator.migrations";
this.simpleName = "CreateDatabase";
this.models = models;
}
public DbGenerator(String packageName, String simpleName, ModelDefinition[] models) {
this.packageName = packageName;
this.simpleName = simpleName;
this.models = models;
}
private void appendOptions(SourceFile sf, StringBuilder sb, Options options) {
sf.staticImports.add(literal.class.getCanonicalName() + ".Map");
sb.append(", Map(");
if(options.size() == 1) {
String key = options.getKeys().iterator().next();
sb.append("\"").append(key).append("\", ").append(options.get(key)).append(')');
} else {
sf.staticImports.add(literal.class.getCanonicalName() + ".e");
for(Iterator<String> iter = options.getKeys().iterator(); iter.hasNext(); ) {
String key = iter.next();
sb.append("\n\t\t\t\te(\"").append(key).append("\", ").append(options.get(key)).append(')');
if(iter.hasNext()) sb.append(", ");
}
sb.append("\n\t\t\t)");
}
}
public DbGenerator generate() {
SourceFile sf = new SourceFile();
for(ModelDefinition model : models) {
model.setOpposites(models);
}
Map<String, ModelTable> tables = new TreeMap<String, ModelTable>();
Map<String, JoinTable> joins = new TreeMap<String, JoinTable>();
Set<ModelTable> joinedModels = new HashSet<ModelTable>();
for(ModelDefinition model : models) {
tables.put(model.getSimpleName(), new ModelTable(sf, model, models));
}
for(ModelDefinition model : models) {
for(ModelRelation relation : model.getRelations()) {
if(relation.hasMany && !relation.isThrough()) {
ModelRelation opposite = relation.getOpposite();
if(opposite == null || opposite.hasMany) {
ModelTable table1 = tables.get(model.getSimpleName());
ModelTable table2 = tables.get(relation.getSimpleType());
JoinTable joinTable = new JoinTable(table1.name, columnName(relation.name), table2.name, columnName(relation.opposite));
if(!joins.containsKey(joinTable.name)) {
joins.put(joinTable.name, joinTable);
joinedModels.add(table1);
joinedModels.add(table2);
}
}
}
}
}
sf.packageName = packageName;
sf.simpleName = simpleName;
sf.superName = AbstractMigration.class.getSimpleName();
sf.imports.add(AbstractMigration.class.getCanonicalName());
sf.imports.add(SQLException.class.getCanonicalName());
StringBuilder sb = new StringBuilder();
sb.append("@Override\npublic void up() throws SQLException {");
for(ModelTable table : tables.values()) {
sb.append('\n');
String var = varName(table.name);
if(table.hasForeignKey() || table.hasIndex() || joinedModels.contains(table)) {
sf.imports.add(Table.class.getCanonicalName());
sb.append("\tTable ").append(var).append(" = createTable(\"").append(table.name).append("\"");
} else {
sb.append("\tcreateTable(\"").append(table.name).append("\"");
}
if(table.columns.isEmpty()) {
sb.append(");\n");
} else {
sb.append(",\n");
for(Iterator<Column> iter = table.columns.iterator(); iter.hasNext(); ) {
Column column = iter.next();
if(DATESTAMPS.equals(column.name)) {
sb.append("\t\tDatestamps(");
} else if(TIMESTAMPS.equals(column.name)) {
- sb.append("\t\t\tTimestamps(");
+ sb.append("\t\tTimestamps(");
} else {
sb.append("\t\t").append(getMethod(column.type)).append("(\"").append(column.name).append("\"");
if(column.options.hasAny()) {
appendOptions(sf, sb, column.options);
}
}
if(iter.hasNext()) {
sb.append("),\n");
} else {
sb.append(")\n");
}
}
sb.append("\t);\n");
}
if(table.hasIndex()) {
for(Index index : table.indexes) {
if(index.unique) {
sb.append("\t").append(var).append(".addUniqueIndex(");
} else {
sb.append("\t").append(var).append(".addIndex(");
}
for(int i = 0; i < index.columns.length; i++) {
if(i != 0) sb.append(", ");
sb.append('"').append(index.columns[i]).append('"');
}
sb.append(");\n");
}
if(!table.hasForeignKey()) {
sb.append("\t").append(var).append(".update();\n");
}
}
}
if(!joins.isEmpty()) {
sb.append('\n');
for(JoinTable join : joins.values()) {
sb.append("\tcreateJoinTable(");
sb.append(join.tableVar1).append(", \"").append(join.column1).append("\", ");
sb.append(join.tableVar2).append(", \"").append(join.column2).append("\");\n");
}
}
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
String var = varName(table.name);
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
sb.append("\n\t").append(var).append(".addForeignKey(\"");
sb.append(fk.column).append("\", \"").append(fk.reference).append('"');
if(fk.options.hasAny()) {
appendOptions(sf, sb, fk.options);
}
sb.append(");");
}
sb.append("\n\t").append(var).append(".update();\n");
}
}
sb.append("}");
sf.methods.put("2", sb.toString());
sb = new StringBuilder();
sb.append("@Override\n\tpublic void down() throws SQLException {\n");
boolean first = true;
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
first = false;
sb.append("\tchangeTable(\"").append(table.name).append("\",");
if(table.foreignKeys.size() == 1) {
sb.append(" removeForeignKey(\"").append(table.foreignKeys.get(0).column).append("\"));\n");
} else {
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
if(i != 0) sb.append(',');
sb.append("\n\t\tremoveForeignKey(\"").append(fk.column).append("\")");
}
sb.append("\n\t);\n");
}
}
}
if(!joins.isEmpty()) {
if(first) {
first = false;
} else {
sb.append('\n');
}
for(JoinTable join : joins.values()) {
sb.append("\tdropJoinTable(\"");
sb.append(join.table1).append("\", \"").append(join.column1).append("\", \"");
sb.append(join.table2).append("\", \"").append(join.column2).append("\");\n");
}
}
if(!first) {
sb.append('\n');
}
for(ModelTable table : tables.values()) {
sb.append("\tdropTable(\"").append(table.name).append("\");\n");
}
sb.append("}");
sf.methods.put("3", sb.toString());
source = sf.toSource();
return this;
}
public String getFullName() {
if(packageName != null) {
return packageName + "." + simpleName;
}
return simpleName;
}
public String getPackageName() {
return packageName;
}
public String getSimpleName() {
return simpleName;
}
public String getSource() {
return source;
}
}
| true | true |
public DbGenerator generate() {
SourceFile sf = new SourceFile();
for(ModelDefinition model : models) {
model.setOpposites(models);
}
Map<String, ModelTable> tables = new TreeMap<String, ModelTable>();
Map<String, JoinTable> joins = new TreeMap<String, JoinTable>();
Set<ModelTable> joinedModels = new HashSet<ModelTable>();
for(ModelDefinition model : models) {
tables.put(model.getSimpleName(), new ModelTable(sf, model, models));
}
for(ModelDefinition model : models) {
for(ModelRelation relation : model.getRelations()) {
if(relation.hasMany && !relation.isThrough()) {
ModelRelation opposite = relation.getOpposite();
if(opposite == null || opposite.hasMany) {
ModelTable table1 = tables.get(model.getSimpleName());
ModelTable table2 = tables.get(relation.getSimpleType());
JoinTable joinTable = new JoinTable(table1.name, columnName(relation.name), table2.name, columnName(relation.opposite));
if(!joins.containsKey(joinTable.name)) {
joins.put(joinTable.name, joinTable);
joinedModels.add(table1);
joinedModels.add(table2);
}
}
}
}
}
sf.packageName = packageName;
sf.simpleName = simpleName;
sf.superName = AbstractMigration.class.getSimpleName();
sf.imports.add(AbstractMigration.class.getCanonicalName());
sf.imports.add(SQLException.class.getCanonicalName());
StringBuilder sb = new StringBuilder();
sb.append("@Override\npublic void up() throws SQLException {");
for(ModelTable table : tables.values()) {
sb.append('\n');
String var = varName(table.name);
if(table.hasForeignKey() || table.hasIndex() || joinedModels.contains(table)) {
sf.imports.add(Table.class.getCanonicalName());
sb.append("\tTable ").append(var).append(" = createTable(\"").append(table.name).append("\"");
} else {
sb.append("\tcreateTable(\"").append(table.name).append("\"");
}
if(table.columns.isEmpty()) {
sb.append(");\n");
} else {
sb.append(",\n");
for(Iterator<Column> iter = table.columns.iterator(); iter.hasNext(); ) {
Column column = iter.next();
if(DATESTAMPS.equals(column.name)) {
sb.append("\t\tDatestamps(");
} else if(TIMESTAMPS.equals(column.name)) {
sb.append("\t\t\tTimestamps(");
} else {
sb.append("\t\t").append(getMethod(column.type)).append("(\"").append(column.name).append("\"");
if(column.options.hasAny()) {
appendOptions(sf, sb, column.options);
}
}
if(iter.hasNext()) {
sb.append("),\n");
} else {
sb.append(")\n");
}
}
sb.append("\t);\n");
}
if(table.hasIndex()) {
for(Index index : table.indexes) {
if(index.unique) {
sb.append("\t").append(var).append(".addUniqueIndex(");
} else {
sb.append("\t").append(var).append(".addIndex(");
}
for(int i = 0; i < index.columns.length; i++) {
if(i != 0) sb.append(", ");
sb.append('"').append(index.columns[i]).append('"');
}
sb.append(");\n");
}
if(!table.hasForeignKey()) {
sb.append("\t").append(var).append(".update();\n");
}
}
}
if(!joins.isEmpty()) {
sb.append('\n');
for(JoinTable join : joins.values()) {
sb.append("\tcreateJoinTable(");
sb.append(join.tableVar1).append(", \"").append(join.column1).append("\", ");
sb.append(join.tableVar2).append(", \"").append(join.column2).append("\");\n");
}
}
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
String var = varName(table.name);
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
sb.append("\n\t").append(var).append(".addForeignKey(\"");
sb.append(fk.column).append("\", \"").append(fk.reference).append('"');
if(fk.options.hasAny()) {
appendOptions(sf, sb, fk.options);
}
sb.append(");");
}
sb.append("\n\t").append(var).append(".update();\n");
}
}
sb.append("}");
sf.methods.put("2", sb.toString());
sb = new StringBuilder();
sb.append("@Override\n\tpublic void down() throws SQLException {\n");
boolean first = true;
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
first = false;
sb.append("\tchangeTable(\"").append(table.name).append("\",");
if(table.foreignKeys.size() == 1) {
sb.append(" removeForeignKey(\"").append(table.foreignKeys.get(0).column).append("\"));\n");
} else {
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
if(i != 0) sb.append(',');
sb.append("\n\t\tremoveForeignKey(\"").append(fk.column).append("\")");
}
sb.append("\n\t);\n");
}
}
}
if(!joins.isEmpty()) {
if(first) {
first = false;
} else {
sb.append('\n');
}
for(JoinTable join : joins.values()) {
sb.append("\tdropJoinTable(\"");
sb.append(join.table1).append("\", \"").append(join.column1).append("\", \"");
sb.append(join.table2).append("\", \"").append(join.column2).append("\");\n");
}
}
if(!first) {
sb.append('\n');
}
for(ModelTable table : tables.values()) {
sb.append("\tdropTable(\"").append(table.name).append("\");\n");
}
sb.append("}");
sf.methods.put("3", sb.toString());
source = sf.toSource();
return this;
}
|
public DbGenerator generate() {
SourceFile sf = new SourceFile();
for(ModelDefinition model : models) {
model.setOpposites(models);
}
Map<String, ModelTable> tables = new TreeMap<String, ModelTable>();
Map<String, JoinTable> joins = new TreeMap<String, JoinTable>();
Set<ModelTable> joinedModels = new HashSet<ModelTable>();
for(ModelDefinition model : models) {
tables.put(model.getSimpleName(), new ModelTable(sf, model, models));
}
for(ModelDefinition model : models) {
for(ModelRelation relation : model.getRelations()) {
if(relation.hasMany && !relation.isThrough()) {
ModelRelation opposite = relation.getOpposite();
if(opposite == null || opposite.hasMany) {
ModelTable table1 = tables.get(model.getSimpleName());
ModelTable table2 = tables.get(relation.getSimpleType());
JoinTable joinTable = new JoinTable(table1.name, columnName(relation.name), table2.name, columnName(relation.opposite));
if(!joins.containsKey(joinTable.name)) {
joins.put(joinTable.name, joinTable);
joinedModels.add(table1);
joinedModels.add(table2);
}
}
}
}
}
sf.packageName = packageName;
sf.simpleName = simpleName;
sf.superName = AbstractMigration.class.getSimpleName();
sf.imports.add(AbstractMigration.class.getCanonicalName());
sf.imports.add(SQLException.class.getCanonicalName());
StringBuilder sb = new StringBuilder();
sb.append("@Override\npublic void up() throws SQLException {");
for(ModelTable table : tables.values()) {
sb.append('\n');
String var = varName(table.name);
if(table.hasForeignKey() || table.hasIndex() || joinedModels.contains(table)) {
sf.imports.add(Table.class.getCanonicalName());
sb.append("\tTable ").append(var).append(" = createTable(\"").append(table.name).append("\"");
} else {
sb.append("\tcreateTable(\"").append(table.name).append("\"");
}
if(table.columns.isEmpty()) {
sb.append(");\n");
} else {
sb.append(",\n");
for(Iterator<Column> iter = table.columns.iterator(); iter.hasNext(); ) {
Column column = iter.next();
if(DATESTAMPS.equals(column.name)) {
sb.append("\t\tDatestamps(");
} else if(TIMESTAMPS.equals(column.name)) {
sb.append("\t\tTimestamps(");
} else {
sb.append("\t\t").append(getMethod(column.type)).append("(\"").append(column.name).append("\"");
if(column.options.hasAny()) {
appendOptions(sf, sb, column.options);
}
}
if(iter.hasNext()) {
sb.append("),\n");
} else {
sb.append(")\n");
}
}
sb.append("\t);\n");
}
if(table.hasIndex()) {
for(Index index : table.indexes) {
if(index.unique) {
sb.append("\t").append(var).append(".addUniqueIndex(");
} else {
sb.append("\t").append(var).append(".addIndex(");
}
for(int i = 0; i < index.columns.length; i++) {
if(i != 0) sb.append(", ");
sb.append('"').append(index.columns[i]).append('"');
}
sb.append(");\n");
}
if(!table.hasForeignKey()) {
sb.append("\t").append(var).append(".update();\n");
}
}
}
if(!joins.isEmpty()) {
sb.append('\n');
for(JoinTable join : joins.values()) {
sb.append("\tcreateJoinTable(");
sb.append(join.tableVar1).append(", \"").append(join.column1).append("\", ");
sb.append(join.tableVar2).append(", \"").append(join.column2).append("\");\n");
}
}
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
String var = varName(table.name);
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
sb.append("\n\t").append(var).append(".addForeignKey(\"");
sb.append(fk.column).append("\", \"").append(fk.reference).append('"');
if(fk.options.hasAny()) {
appendOptions(sf, sb, fk.options);
}
sb.append(");");
}
sb.append("\n\t").append(var).append(".update();\n");
}
}
sb.append("}");
sf.methods.put("2", sb.toString());
sb = new StringBuilder();
sb.append("@Override\n\tpublic void down() throws SQLException {\n");
boolean first = true;
for(ModelTable table : tables.values()) {
if(table.hasForeignKey()) {
first = false;
sb.append("\tchangeTable(\"").append(table.name).append("\",");
if(table.foreignKeys.size() == 1) {
sb.append(" removeForeignKey(\"").append(table.foreignKeys.get(0).column).append("\"));\n");
} else {
for(int i = 0; i < table.foreignKeys.size(); i++) {
ForeignKey fk = table.foreignKeys.get(i);
if(i != 0) sb.append(',');
sb.append("\n\t\tremoveForeignKey(\"").append(fk.column).append("\")");
}
sb.append("\n\t);\n");
}
}
}
if(!joins.isEmpty()) {
if(first) {
first = false;
} else {
sb.append('\n');
}
for(JoinTable join : joins.values()) {
sb.append("\tdropJoinTable(\"");
sb.append(join.table1).append("\", \"").append(join.column1).append("\", \"");
sb.append(join.table2).append("\", \"").append(join.column2).append("\");\n");
}
}
if(!first) {
sb.append('\n');
}
for(ModelTable table : tables.values()) {
sb.append("\tdropTable(\"").append(table.name).append("\");\n");
}
sb.append("}");
sf.methods.put("3", sb.toString());
source = sf.toSource();
return this;
}
|
diff --git a/srcj/com/sun/electric/tool/io/input/HSpiceOut.java b/srcj/com/sun/electric/tool/io/input/HSpiceOut.java
index d899e2816..9bd8c6476 100644
--- a/srcj/com/sun/electric/tool/io/input/HSpiceOut.java
+++ b/srcj/com/sun/electric/tool/io/input/HSpiceOut.java
@@ -1,1008 +1,1009 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: HSpiceOut.java
* Input/output tool: reader for HSpice output (tr, pa, ac, sw, mt)
* Written by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.input;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.tool.simulation.AnalogAnalysis;
import com.sun.electric.tool.simulation.AnalogSignal;
import com.sun.electric.tool.simulation.Analysis;
import com.sun.electric.tool.simulation.Stimuli;
import com.sun.electric.tool.simulation.Signal;
import com.sun.electric.tool.simulation.ScalarSignal;
import com.sun.electric.tool.simulation.ScalarSample;
import com.sun.electric.database.geometry.btree.*;
import com.sun.electric.database.geometry.btree.unboxed.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.io.*;
import com.sun.electric.tool.io.input.*;
import com.sun.electric.database.geometry.btree.*;
import com.sun.electric.tool.simulation.*;
/**
* Class for reading and displaying waveforms from HSpice output.
* This includes transient information in .tr and .pa files (.pa0/.tr0, .pa1/.tr1, ...)
* It also includes AC analysis in .ac files; DC analysis in .sw files;
* and Measurements in .mt files.
*
* While trying to debug the condition count handling, these test cases were observed:
* CASE VERSION ANALYSIS NUMNOI SWEEPCNT CNDCNT CONDITIONS
* H01 9007 TR 0 4 1 bma_w
* H02 9007 TR 36 19 1 sweepv
* H03 9007 TR 2 30 1 MONTE_CARLO
* DC 258 30 1 MONTE_CARLO
* H04 9007 TR 2 7 1 TEMPERATURE
* DC 0 0 0
* AC 0 6 1 bigcap
* H05 9601 TR 0 0 0
* H06 9601 TR 0 0 0
* H07 9601 TR 2 25 3 data_tim, inbufstr, outloadstr (sweep header has 2 numbers)
* H08 9601 TR 4 3 2 ccdata, cc
* AC 4 2 1 lpvar (***CRASHES***)
* H09 9601 TR 0 3 3 rdata, r, c (sweep header has 2 numbers)
* AC 0 3 3 rdata, r, c (sweep header has 2 numbers)
* H10 9601 TR 0 4 8 rdata, r0, r1, r2, r3, r4, c0, c1 (sweep header has 7 numbers)
* AC 0 4 8 rdata, r0, r1, r2, r3, r4, c0, c1 (sweep header has 7 numbers)
*/
public class HSpiceOut extends Input<Stimuli>
{
private static final boolean DEBUGCONDITIONS = false;
/** true if tr/ac/sw file is binary */ private boolean isTRACDCBinary;
/** true if binary tr/ac/sw file has bytes swapped */ private boolean isTRACDCBinarySwapped;
/** the raw file base */ private String fileBase;
/** the "tr" file extension (tr0, tr1, ...): transient */ private String trExtension;
/** the "sw" file extension (sw0, sw1, ...): DC */ private String swExtension;
/** the "ic" file extension (ic0, ic1, ...): old DC */ private String icExtension;
/** the "ac" file extension (ac0, ac1, ...): AC */ private String acExtension;
/** the "mt" file extension (mt0, mt1, ...): measurement */ private String mtExtension;
/** the "pa" file extension (pa0, pa1, ...): long names */ private String paExtension;
private int binaryTRACDCSize, binaryTRACDCPosition;
private boolean eofReached;
private byte [] binaryTRACDCBuffer;
/**
* Class to hold HSpice name associations from the .paX file
*/
private static class PALine
{
int number;
String string;
}
HSpiceOut() {}
/**
* Method to read HSpice output files.
* @param sd Stimuli associated to the reading.
* @param fileURL the URL to one of the output files.
* @param cell the Cell associated with these HSpice output files.
*/
protected Stimuli processInput(URL fileURL, Cell cell)
throws IOException
{
Stimuli sd = new Stimuli();
sd.setCell(cell);
// figure out file names
fileBase = fileURL.getFile();
trExtension = "tr0";
swExtension = "sw0";
icExtension = "ic0";
acExtension = "ac0";
mtExtension = "mt0";
paExtension = "pa0";
int dotPos = fileBase.lastIndexOf('.');
if (dotPos > 0)
{
String extension = fileBase.substring(dotPos+1);
fileBase = fileBase.substring(0, dotPos);
if (extension.startsWith("tr") || extension.startsWith("sw") || extension.startsWith("ic") ||
extension.startsWith("ac") || extension.startsWith("mt") || extension.startsWith("pa"))
{
trExtension = "tr" + extension.substring(2);
swExtension = "sw" + extension.substring(2);
icExtension = "ic" + extension.substring(2);
acExtension = "ac" + extension.substring(2);
mtExtension = "mt" + extension.substring(2);
paExtension = "pa" + extension.substring(2);
}
}
// the .pa file has name information
List<PALine> paList = readPAFile(fileURL);
// read Transient analysis data (.tr file)
addTRData(sd, paList, fileURL);
// read DC analysis data (.sw file)
addDCData(sd, paList, fileURL);
// read AC analysis data (.ac file)
addACData(sd, paList, fileURL);
// read measurement data (.mt file)
addMeasurementData(sd, fileURL);
// return the simulation data
return sd;
}
/**
* Method to find the ".mt" file and read measurement data.
* @param sd the Stimuli to add this measurement data to.
* @param fileURL the URL to the ".tr" file.
* @throws IOException
*/
private void addMeasurementData(Stimuli sd, URL fileURL)
throws IOException
{
// find the associated ".mt" name file
URL mtURL = null;
try
{
mtURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + mtExtension);
} catch (java.net.MalformedURLException e)
{
}
if (mtURL == null) return;
if (!TextUtils.URLExists(mtURL)) return;
if (openTextInput(mtURL)) return;
System.out.println("Reading HSpice measurements '" + mtURL.getFile() + "'");
AnalogAnalysis an = new AnalogAnalysis(sd, AnalogAnalysis.ANALYSIS_MEAS, false);
List<String> measurementNames = new ArrayList<String>();
HashMap<String,List<Double>> measurementData = new HashMap<String,List<Double>>();
String lastLine = null;
for(;;)
{
// get line from file
String nextLine = lastLine;
if (nextLine == null)
{
nextLine = lineReader.readLine();
if (nextLine == null) break;
}
if (nextLine.startsWith("$") || nextLine.startsWith(".")) continue;
String [] keywords = breakMTLine(nextLine, false);
if (keywords.length == 0) break;
// gather measurement names on the first time out
if (measurementNames.size() == 0)
{
for(int i=0; i<keywords.length; i++)
measurementNames.add(keywords[i]);
for(;;)
{
lastLine = lineReader.readLine();
if (lastLine == null) break;
keywords = breakMTLine(lastLine, true);
if (keywords.length == 0) { lastLine = null; break; }
if (TextUtils.isANumber(keywords[0])) break;
for(int i=0; i<keywords.length; i++)
if (keywords[i].length() > 0)
measurementNames.add(keywords[i]);
}
for(String mName : measurementNames)
{
measurementData.put(mName, new ArrayList<Double>());
}
continue;
}
// get data values
int index = 0;
for(int i=0; i<keywords.length; i++)
{
if (keywords[i].length() == 0) continue;
String mName = measurementNames.get(index++);
List<Double> mData = measurementData.get(mName);
mData.add(new Double(TextUtils.atof(keywords[i])));
}
for(;;)
{
if (index >= measurementNames.size()) break;
lastLine = lineReader.readLine();
if (lastLine == null) break;
keywords = breakMTLine(lastLine, true);
if (keywords.length == 0) break;
for(int i=0; i<keywords.length; i++)
{
if (keywords[i].length() == 0) continue;
String mName = measurementNames.get(index++);
List<Double> mData = measurementData.get(mName);
mData.add(new Double(TextUtils.atof(keywords[i])));
}
}
lastLine = null;
continue;
}
// convert this to a list of Measurements
List<Double> argMeas = measurementData.get(measurementNames.get(0));
an.buildCommonTime(argMeas.size());
for (int i = 0; i < argMeas.size(); i++)
an.setCommonTime(i, argMeas.get(i).doubleValue());
List<AnalogSignal> measData = new ArrayList<AnalogSignal>();
for(String mName : measurementNames)
{
List<Double> mData = measurementData.get(mName);
double[] values = new double[mData.size()];
for(int i=0; i<mData.size(); i++) values[i] = mData.get(i).doubleValue();
// special case with the "alter#" name...remove the "#"
if (mName.equals("alter#")) mName = "alter";
AnalogSignal as = an.addSignal(mName, null, values);
measData.add(as);
}
closeInput();
}
/**
* Method to parse a line from a measurement (.mt0) file.
* @param line the line from the file.
* @param continuation true if the line is supposed to be a continuation
* after the first line.
* @return an array of strings on the line (zero-length if at end).
*/
private String[] breakMTLine(String line, boolean continuation)
{
List<String> strings = new ArrayList<String>();
for(int i=1; ; )
{
if (line.length() <= i+1) break;
int end = i+17;
if (end > line.length()) end = line.length();
while (end < line.length() && line.charAt(end-1) != ' ') end++;
String part = line.substring(i, end).trim();
// if (i == 1)
// {
// // first token: make sure it is blank if a continuation
// if (continuation && part.length() > 0) return new String[0];
// }
if (part.length() > 0) strings.add(part.trim());
i = end;
}
int actualSize = strings.size();
String [] retVal = new String[actualSize];
for(int i=0; i<actualSize; i++) retVal[i] = strings.get(i);
return retVal;
}
/**
* Method to find the ".tr" file and read transient data.
* @param sd the Stimuli to add this transient data to.
* @param fileURL the URL to the ".tr" file.
* @throws IOException
*/
private void addTRData(Stimuli sd, List<PALine> paList, URL fileURL)
throws IOException
{
// find the associated ".tr" name file
URL swURL = null;
try
{
swURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + trExtension);
} catch (java.net.MalformedURLException e) {}
if (swURL == null) return;
if (!TextUtils.URLExists(swURL)) return;
// process the DC data
readTRDCACFile(sd, swURL, paList, Analysis.ANALYSIS_TRANS);
}
/**
* Method to find the ".sw" file and read DC data.
* @param sd the Stimuli to add this DC data to.
* @param fileURL the URL to the ".tr" file.
* @throws IOException
*/
private void addDCData(Stimuli sd, List<PALine> paList, URL fileURL)
throws IOException
{
// find the associated ".sw" name file
URL swURL = null;
try
{
swURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + swExtension);
} catch (java.net.MalformedURLException e) {}
if (swURL != null && TextUtils.URLExists(swURL))
{
// process the DC data
readTRDCACFile(sd, swURL, paList, Analysis.ANALYSIS_DC);
return;
}
// no associated ".sw" file, look for an ".ic" name file
URL icURL = null;
try
{
icURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + icExtension);
} catch (java.net.MalformedURLException e) {}
if (icURL != null && TextUtils.URLExists(icURL))
{
// can't process the DC data
System.out.println("WARNING: Cannot read old DC format file (." + icExtension +
")...must provide new format (." + swExtension + "): " + fileBase + "." + icExtension);
return;
}
}
/**
* Method to find the ".ac" file and read AC data.
* @param sd the Stimuli to add this AC data to.
* @param fileURL the URL to the ".tr" file.
* @throws IOException
*/
private void addACData(Stimuli sd, List<PALine> paList, URL fileURL)
throws IOException
{
// find the associated ".ac" name file
URL acURL = null;
try
{
acURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + acExtension);
} catch (java.net.MalformedURLException e) {}
if (acURL == null) return;
if (!TextUtils.URLExists(acURL)) return;
// process the AC data
readTRDCACFile(sd, acURL, paList, Analysis.ANALYSIS_AC);
}
/**
* Method to read the "pa" file with full symbol names.
* These files can end in "0", "1", "2",...
* @param fileURL the URL to the simulation output file
* @return a list of PALine objects that describe the name mapping file entries.
*/
private List<PALine> readPAFile(URL fileURL)
throws IOException
{
// find the associated ".pa" name file
URL paURL = null;
try
{
paURL = new URL(fileURL.getProtocol(), fileURL.getHost(), fileURL.getPort(), fileBase + "." + paExtension);
} catch (java.net.MalformedURLException e) {}
if (paURL == null) return null;
if (!TextUtils.URLExists(paURL)) return null;
if (openTextInput(paURL)) return null;
List<PALine> paList = new ArrayList<PALine>();
for(;;)
{
// get line from file
String nextLine = lineReader.readLine();
if (nextLine == null) break;
// break into number and name
String trimLine = nextLine.trim();
int spacePos = trimLine.indexOf(' ');
if (spacePos > 0)
{
// save it in a PALine object
PALine pl = new PALine();
pl.number = TextUtils.atoi(trimLine, 0, 10);
pl.string = removeLeadingX(trimLine.substring(spacePos+1).trim());
paList.add(pl);
}
}
closeInput();
return paList;
}
private void readTRDCACFile(Stimuli sd, URL fileURL, List<PALine> paList, Analysis.AnalysisType analysisType)
throws IOException
{
if (openBinaryInput(fileURL)) return;
eofReached = false;
resetBinaryTRACDCReader();
AnalogAnalysis an = new AnalogAnalysis(sd, analysisType, false);
startProgressDialog("HSpice " + analysisType.toString() + " analysis", fileURL.getFile());
System.out.println("Reading HSpice " + analysisType.toString() + " analysis '" + fileURL.getFile() + "'");
// get number of nodes
int nodcnt = getHSpiceInt();
// get number of special items
int numnoi = getHSpiceInt();
// get number of conditions
int cndcnt = getHSpiceInt();
/*
* Although this isn't documented anywhere, it appears that the 4th
* number in the file is a multiplier for the first, which allows
* there to be more than 10000 nodes.
*/
StringBuffer line = new StringBuffer();
for(int j=0; j<4; j++) line.append((char)getByteFromFile());
int multiplier = TextUtils.atoi(line.toString(), 0, 10);
nodcnt += multiplier * 10000;
int numSignals = numnoi + nodcnt - 1;
if (numSignals <= 0)
{
System.out.println("Error reading " + fileURL.getFile());
closeInput();
stopProgressDialog();
return;
}
// get version number (known to work with 9007, 9601)
int version = getHSpiceInt();
if (version != 9007 && version != 9601)
System.out.println("Warning: may not be able to read HSpice files of type " + version);
// ignore the unused/title information (4+72 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// ignore the date/time information (16 characters)
line = new StringBuffer();
for(int j=0; j<16; j++) line.append((char)getByteFromFile());
// ignore the copywrite information (72 characters over line break)
line = new StringBuffer();
for(int j=0; j<72; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get number of sweeps
int sweepcnt = getHSpiceInt();
if (DEBUGCONDITIONS)
System.out.println("++++++++++++++++++++ VERSION="+version+" SWEEPCNT="+sweepcnt+" CNDCNT="+cndcnt+" NUMNOI="+numnoi+" MULTIPLIER="+multiplier);
if (cndcnt == 0) sweepcnt = 0;
// ignore the Monte Carlo information (76 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get the type of each signal
String [] signalNames = new String[numSignals];
int [] signalTypes = new int[numSignals];
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(int j=0; j<8; j++)
{
int l = getByteFromFile();
line.append((char)l);
if (!isTRACDCBinary && l == '\n') j--;
}
if (k == 0) continue;
int l = k - nodcnt;
if (k < nodcnt) l = k + numnoi - 1;
String lineStr = line.toString().trim();
signalTypes[l] = TextUtils.atoi(lineStr, 0, 10);
}
boolean paMissingWarned = false;
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ')
{
if (line.length() != 0) break;
// if name starts with blank, skip until non-blank
for(;;)
{
l = getByteFromFile();
if (l != ' ') break;
}
}
line.append((char)l);
if (version == 9007 && line.length() >= 16) break;
}
int j = line.length();
int l = (j+16) / 16 * 16 - 1;
if (version == 9007)
{
l = (j+15) / 16 * 16 - 1;
}
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (k == 0) continue;
// convert name if there is a colon in it
int startPos = 0;
int openPos = line.indexOf("(");
if (openPos >= 0) startPos = openPos+1;
for(j=startPos; j<line.length(); j++)
{
if (line.charAt(j) == ':') break;
if (!TextUtils.isDigit(line.charAt(j))) break;
}
if (j < line.length() && line.charAt(j) == ':')
{
l = TextUtils.atoi(line.toString().substring(startPos), 0, 10);
PALine foundPALine = null;
if (paList == null)
{
if (!paMissingWarned)
System.out.println("Warning: there should be a ." + paExtension + " file with extra signal names");
paMissingWarned = true;
} else
{
for(PALine paLine : paList)
{
if (paLine.number == l) { foundPALine = paLine; break; }
}
}
if (foundPALine != null)
{
StringBuffer newSB = new StringBuffer();
newSB.append(line.substring(0, startPos));
newSB.append(foundPALine.string);
newSB.append(line.substring(j+1));
line = newSB;
}
} else
{
if (line.indexOf(".") >= 0)
{
String fixedLine = removeLeadingX(line.toString());
line = new StringBuffer();
line.append(fixedLine);
}
}
// move parenthesis from the start to the last name
openPos = line.indexOf("(");
if (openPos >= 0)
{
String parenPrefix = line.substring(0, openPos+1);
int lastDot = line.lastIndexOf(".");
if (lastDot >= 0)
{
StringBuffer newSB = new StringBuffer();
if (parenPrefix.equalsIgnoreCase("v("))
{
// just ignore the V()
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(line.substring(lastDot+1, line.length()-1));
} else
{
// move the parenthetical wrapper to the last dotted piece
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(parenPrefix);
newSB.append(line.substring(lastDot+1));
}
line = newSB;
} else if (parenPrefix.equalsIgnoreCase("v("))
{
StringBuffer newSB = new StringBuffer();
// just ignore the V()
newSB.append(line.substring(openPos+1, line.length()-1));
line = newSB;
}
}
if (k < nodcnt) l = k + numnoi - 1; else l = k - nodcnt;
signalNames[l] = line.toString();
}
// read (and ignore) condition information
for(int c=0; c<cndcnt; c++)
{
int j = 0;
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ') break;
line.append((char)l);
j++;
if (j >= 16) break;
}
int l = (j+15) / 16 * 16 - 1;
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (DEBUGCONDITIONS)
System.out.println("CONDITION "+(c+1)+" IS "+line.toString());
}
// read the end-of-header marker
line = new StringBuffer();
if (!isTRACDCBinary)
{
// finish line, ensure the end-of-header
for(int j=0; ; j++)
{
int l = getByteFromFile();
if (l == '\n') break;
if (j < 4) line.append(l);
}
} else
{
// gather end-of-header string
for(int j=0; j<4; j++)
line.append((char)getByteFromFile());
}
if (!line.toString().equals("$&%#"))
{
System.out.println("HSpice header improperly terminated (got "+line.toString()+")");
closeInput();
stopProgressDialog();
return;
}
resetBinaryTRACDCReader();
// preprocess signal names to remove constant prefix (this code also occurs in VerilogOut.readVerilogFile)
String constantPrefix = null;
boolean hasPrefix = true;
for(int k=0; k<numSignals; k++)
{
String name = signalNames[k];
int dotPos = name.indexOf('.');
if (dotPos < 0) continue;
String prefix = name.substring(0, dotPos);
if (constantPrefix == null) constantPrefix = prefix;
if (!constantPrefix.equals(prefix)) { hasPrefix = false; break; }
}
if (!hasPrefix) constantPrefix = null; else {
String fileName = fileURL.getFile();
int pos = fileName.lastIndexOf(File.separatorChar);
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.lastIndexOf('/');
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.indexOf('.');
if (pos >= 0) fileName = fileName.substring(0, pos);
if (fileName.equals(constantPrefix)) constantPrefix += "."; else
constantPrefix = null;
}
AnalogSignal[] signals = new AnalogSignal[numSignals];
for(int k=0; k<numSignals; k++) {
String name = signalNames[k];
if (constantPrefix != null &&
name.startsWith(constantPrefix))
name = name.substring(constantPrefix.length());
String context = null;
int lastDotPos = name.lastIndexOf('.');
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos+1);
}
signals[k] = new AnalogSignal(an, name, context);
}
// setup the simulation information
boolean isComplex = analysisType == Analysis.ANALYSIS_AC;
int sweepCounter = sweepcnt;
for(;;) {
// get sweep info
String sweepName = "";
if (sweepcnt > 0) {
float sweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF before sweep data"); break; }
sweepName = TextUtils.formatDouble(sweepValue);
if (DEBUGCONDITIONS) System.out.println("READING SWEEP NUMBER: "+sweepValue);
// if there are more than 2 conditions, read extra sweep values
for(int i=2; i<cndcnt; i++) {
float anotherSweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF reading sweep header"); break; }
sweepName += "," + TextUtils.formatDouble(anotherSweepValue);
if (DEBUGCONDITIONS) System.out.println(" EXTRA SWEEP NUMBER: "+anotherSweepValue);
}
sweepName = ":"+sweepName;
}
for(;;) {
// get the first number, see if it terminates
float time = getHSpiceFloat(true);
if (eofReached) break;
// get a row of numbers
for(int k=0; k<numSignals; k++) {
if (isComplex) {
float realPart = getHSpiceFloat(false);
float imagPart = getHSpiceFloat(false);
/*
signals[k].addSample(time, new ComplexSample(realPart, imagPart));
*/
signals[k].addSample(time, new ScalarSample(realPart));
} else {
- signals[k].addSample(time, new ScalarSample(getHSpiceFloat(false)));
+ if (signals[k].getSample(time)==null)
+ signals[k].addSample(time, new ScalarSample(getHSpiceFloat(false)));
}
if (eofReached) {
System.out.println("EOF in the middle of the data (at " + k + " out of " + numSignals +")");
break;
}
}
if (eofReached) { System.out.println("EOF before the end of the data"); break; }
}
sweepCounter--;
if (sweepCounter <= 0) break;
eofReached = false;
}
closeInput();
stopProgressDialog();
System.out.println("Done reading " + analysisType.toString() + " analysis");
}
/**
* Method to reset the binary block pointer (done between the header and
* the data).
*/
private void resetBinaryTRACDCReader()
{
binaryTRACDCSize = 0;
binaryTRACDCPosition = 0;
}
/**
* Method to read the next block of tr, sw, or ac data.
* @param firstbyteread true to skip the first byte.
* @return true on EOF.
*/
private boolean readBinaryTRACDCBlock(boolean firstbyteread)
throws IOException
{
// read the first word of a binary block
if (!firstbyteread)
{
if (dataInputStream.read() == -1) return true;
updateProgressDialog(1);
}
for(int i=0; i<3; i++)
if (dataInputStream.read() == -1) return true;
updateProgressDialog(3);
// read the number of 8-byte blocks
int blocks = 0;
for(int i=0; i<4; i++)
{
int uval = dataInputStream.read();
if (uval == -1) return true;
if (isTRACDCBinarySwapped) blocks = ((blocks >> 8) & 0xFFFFFF) | ((uval&0xFF) << 24); else
blocks = (blocks << 8) | uval;
}
updateProgressDialog(4);
// skip the dummy word
for(int i=0; i<4; i++)
if (dataInputStream.read() == -1) return true;
updateProgressDialog(4);
// read the number of bytes
int bytes = 0;
for(int i=0; i<4; i++)
{
int uval = dataInputStream.read();
if (uval == -1) return true;
if (isTRACDCBinarySwapped) bytes = ((bytes >> 8) & 0xFFFFFF) | ((uval&0xFF) << 24); else
bytes = (bytes << 8) | uval;
}
updateProgressDialog(4);
// now read the data
if (bytes > 8192)
{
System.out.println("ERROR: block is " + bytes + " long, but limit is 8192");
bytes = 8192;
}
int amtread = dataInputStream.read(binaryTRACDCBuffer, 0, bytes);
if (amtread != bytes)
{
System.out.println("Expected to read " + bytes + " bytes but got only " + amtread);
return true;
}
updateProgressDialog(bytes);
// read the trailer count
int trailer = 0;
for(int i=0; i<4; i++)
{
int uval = dataInputStream.read();
if (uval == -1) return true;
if (isTRACDCBinarySwapped) trailer = ((trailer >> 8) & 0xFFFFFF) | ((uval&0xFF) << 24); else
trailer = (trailer << 8) | uval;
}
if (trailer != bytes)
{
System.out.println("Block trailer claims block had " + trailer + " bytes but block really had " + bytes);
return true;
}
updateProgressDialog(4);
// set pointers for the buffer
binaryTRACDCPosition = 0;
binaryTRACDCSize = bytes;
return false;
}
/**
* Method to get the next character from the simulator.
* @return the next character (EOF at end of file).
*/
private int getByteFromFile()
throws IOException
{
if (byteCount == 0)
{
// start of HSpice file: see if it is binary or ascii
int i = dataInputStream.read();
if (i == -1) return(i);
updateProgressDialog(1);
if (i == 0 || i == 4)
{
isTRACDCBinary = true;
isTRACDCBinarySwapped = false;
if (i == 4) isTRACDCBinarySwapped = true;
binaryTRACDCBuffer = new byte[8192];
if (readBinaryTRACDCBlock(true)) return(-1);
} else
{
isTRACDCBinary = false;
return(i);
}
}
if (isTRACDCBinary)
{
if (binaryTRACDCPosition >= binaryTRACDCSize)
{
if (readBinaryTRACDCBlock(false))
return(-1);
}
int val = binaryTRACDCBuffer[binaryTRACDCPosition];
binaryTRACDCPosition++;
return val&0xFF;
}
int i = dataInputStream.read();
updateProgressDialog(1);
return i;
}
/**
* Method to get the next 4-byte integer from the simulator.
* @return the next integer.
*/
private int getHSpiceInt()
throws IOException
{
StringBuffer line = new StringBuffer();
for(int j=0; j<4; j++) line.append((char)getByteFromFile());
return TextUtils.atoi(line.toString().trim(), 0, 10);
}
/**
* Method to read the next floating point number from the HSpice file.
* @return the next number. Sets the global "eofReached" true on EOF.
*/
private float getHSpiceFloat(boolean testEOFValue)
throws IOException
{
if (!isTRACDCBinary)
{
StringBuffer line = new StringBuffer();
for(int j=0; j<11; j++)
{
int l = getByteFromFile();
if (l == -1)
{
eofReached = true; return 0;
}
line.append((char)l);
if (l == '\n') j--;
}
String result = line.toString();
if (testEOFValue && result.equals("0.10000E+31")) { eofReached = true; return 0; }
return (float)TextUtils.atof(result);
}
// binary format
int fi0 = getByteFromFile();
int fi1 = getByteFromFile();
int fi2 = getByteFromFile();
int fi3 = getByteFromFile();
if (fi0 < 0 || fi1 < 0 || fi2 < 0 || fi3 < 0)
{
eofReached = true;
return 0;
}
fi0 &= 0xFF;
fi1 &= 0xFF;
fi2 &= 0xFF;
fi3 &= 0xFF;
int fi = 0;
if (isTRACDCBinarySwapped)
{
fi = (fi3 << 24) | (fi2 << 16) | (fi1 << 8) | fi0;
} else
{
fi = (fi0 << 24) | (fi1 << 16) | (fi2 << 8) | fi3;
}
float f = Float.intBitsToFloat(fi);
// the termination value (in hex) is 71 49 F2 CA
if (testEOFValue && f > 1.00000000E30 && f < 1.00000002E30)
{
eofReached = true;
return 0;
}
return f;
}
/**
* Method to remove the leading "x" character in each dotted part of a string.
* HSpice decides to add "x" in front of every cell name, so the path "me.you"
* appears as "xme.xyou".
* @param name the string from HSpice.
* @return the string without leading "X"s.
*/
static String removeLeadingX(String name)
{
// remove all of the "x" characters at the start of every instance name
int dotPos = -1;
while (name.indexOf('.', dotPos+1) >= 0)
{
int xPos = dotPos + 1;
if (name.length() > xPos && name.charAt(xPos) == 'x')
{
name = name.substring(0, xPos) + name.substring(xPos+1);
}
dotPos = name.indexOf('.', xPos);
if (dotPos < 0) break;
}
return name;
}
}
| true | true |
private void readTRDCACFile(Stimuli sd, URL fileURL, List<PALine> paList, Analysis.AnalysisType analysisType)
throws IOException
{
if (openBinaryInput(fileURL)) return;
eofReached = false;
resetBinaryTRACDCReader();
AnalogAnalysis an = new AnalogAnalysis(sd, analysisType, false);
startProgressDialog("HSpice " + analysisType.toString() + " analysis", fileURL.getFile());
System.out.println("Reading HSpice " + analysisType.toString() + " analysis '" + fileURL.getFile() + "'");
// get number of nodes
int nodcnt = getHSpiceInt();
// get number of special items
int numnoi = getHSpiceInt();
// get number of conditions
int cndcnt = getHSpiceInt();
/*
* Although this isn't documented anywhere, it appears that the 4th
* number in the file is a multiplier for the first, which allows
* there to be more than 10000 nodes.
*/
StringBuffer line = new StringBuffer();
for(int j=0; j<4; j++) line.append((char)getByteFromFile());
int multiplier = TextUtils.atoi(line.toString(), 0, 10);
nodcnt += multiplier * 10000;
int numSignals = numnoi + nodcnt - 1;
if (numSignals <= 0)
{
System.out.println("Error reading " + fileURL.getFile());
closeInput();
stopProgressDialog();
return;
}
// get version number (known to work with 9007, 9601)
int version = getHSpiceInt();
if (version != 9007 && version != 9601)
System.out.println("Warning: may not be able to read HSpice files of type " + version);
// ignore the unused/title information (4+72 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// ignore the date/time information (16 characters)
line = new StringBuffer();
for(int j=0; j<16; j++) line.append((char)getByteFromFile());
// ignore the copywrite information (72 characters over line break)
line = new StringBuffer();
for(int j=0; j<72; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get number of sweeps
int sweepcnt = getHSpiceInt();
if (DEBUGCONDITIONS)
System.out.println("++++++++++++++++++++ VERSION="+version+" SWEEPCNT="+sweepcnt+" CNDCNT="+cndcnt+" NUMNOI="+numnoi+" MULTIPLIER="+multiplier);
if (cndcnt == 0) sweepcnt = 0;
// ignore the Monte Carlo information (76 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get the type of each signal
String [] signalNames = new String[numSignals];
int [] signalTypes = new int[numSignals];
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(int j=0; j<8; j++)
{
int l = getByteFromFile();
line.append((char)l);
if (!isTRACDCBinary && l == '\n') j--;
}
if (k == 0) continue;
int l = k - nodcnt;
if (k < nodcnt) l = k + numnoi - 1;
String lineStr = line.toString().trim();
signalTypes[l] = TextUtils.atoi(lineStr, 0, 10);
}
boolean paMissingWarned = false;
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ')
{
if (line.length() != 0) break;
// if name starts with blank, skip until non-blank
for(;;)
{
l = getByteFromFile();
if (l != ' ') break;
}
}
line.append((char)l);
if (version == 9007 && line.length() >= 16) break;
}
int j = line.length();
int l = (j+16) / 16 * 16 - 1;
if (version == 9007)
{
l = (j+15) / 16 * 16 - 1;
}
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (k == 0) continue;
// convert name if there is a colon in it
int startPos = 0;
int openPos = line.indexOf("(");
if (openPos >= 0) startPos = openPos+1;
for(j=startPos; j<line.length(); j++)
{
if (line.charAt(j) == ':') break;
if (!TextUtils.isDigit(line.charAt(j))) break;
}
if (j < line.length() && line.charAt(j) == ':')
{
l = TextUtils.atoi(line.toString().substring(startPos), 0, 10);
PALine foundPALine = null;
if (paList == null)
{
if (!paMissingWarned)
System.out.println("Warning: there should be a ." + paExtension + " file with extra signal names");
paMissingWarned = true;
} else
{
for(PALine paLine : paList)
{
if (paLine.number == l) { foundPALine = paLine; break; }
}
}
if (foundPALine != null)
{
StringBuffer newSB = new StringBuffer();
newSB.append(line.substring(0, startPos));
newSB.append(foundPALine.string);
newSB.append(line.substring(j+1));
line = newSB;
}
} else
{
if (line.indexOf(".") >= 0)
{
String fixedLine = removeLeadingX(line.toString());
line = new StringBuffer();
line.append(fixedLine);
}
}
// move parenthesis from the start to the last name
openPos = line.indexOf("(");
if (openPos >= 0)
{
String parenPrefix = line.substring(0, openPos+1);
int lastDot = line.lastIndexOf(".");
if (lastDot >= 0)
{
StringBuffer newSB = new StringBuffer();
if (parenPrefix.equalsIgnoreCase("v("))
{
// just ignore the V()
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(line.substring(lastDot+1, line.length()-1));
} else
{
// move the parenthetical wrapper to the last dotted piece
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(parenPrefix);
newSB.append(line.substring(lastDot+1));
}
line = newSB;
} else if (parenPrefix.equalsIgnoreCase("v("))
{
StringBuffer newSB = new StringBuffer();
// just ignore the V()
newSB.append(line.substring(openPos+1, line.length()-1));
line = newSB;
}
}
if (k < nodcnt) l = k + numnoi - 1; else l = k - nodcnt;
signalNames[l] = line.toString();
}
// read (and ignore) condition information
for(int c=0; c<cndcnt; c++)
{
int j = 0;
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ') break;
line.append((char)l);
j++;
if (j >= 16) break;
}
int l = (j+15) / 16 * 16 - 1;
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (DEBUGCONDITIONS)
System.out.println("CONDITION "+(c+1)+" IS "+line.toString());
}
// read the end-of-header marker
line = new StringBuffer();
if (!isTRACDCBinary)
{
// finish line, ensure the end-of-header
for(int j=0; ; j++)
{
int l = getByteFromFile();
if (l == '\n') break;
if (j < 4) line.append(l);
}
} else
{
// gather end-of-header string
for(int j=0; j<4; j++)
line.append((char)getByteFromFile());
}
if (!line.toString().equals("$&%#"))
{
System.out.println("HSpice header improperly terminated (got "+line.toString()+")");
closeInput();
stopProgressDialog();
return;
}
resetBinaryTRACDCReader();
// preprocess signal names to remove constant prefix (this code also occurs in VerilogOut.readVerilogFile)
String constantPrefix = null;
boolean hasPrefix = true;
for(int k=0; k<numSignals; k++)
{
String name = signalNames[k];
int dotPos = name.indexOf('.');
if (dotPos < 0) continue;
String prefix = name.substring(0, dotPos);
if (constantPrefix == null) constantPrefix = prefix;
if (!constantPrefix.equals(prefix)) { hasPrefix = false; break; }
}
if (!hasPrefix) constantPrefix = null; else {
String fileName = fileURL.getFile();
int pos = fileName.lastIndexOf(File.separatorChar);
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.lastIndexOf('/');
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.indexOf('.');
if (pos >= 0) fileName = fileName.substring(0, pos);
if (fileName.equals(constantPrefix)) constantPrefix += "."; else
constantPrefix = null;
}
AnalogSignal[] signals = new AnalogSignal[numSignals];
for(int k=0; k<numSignals; k++) {
String name = signalNames[k];
if (constantPrefix != null &&
name.startsWith(constantPrefix))
name = name.substring(constantPrefix.length());
String context = null;
int lastDotPos = name.lastIndexOf('.');
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos+1);
}
signals[k] = new AnalogSignal(an, name, context);
}
// setup the simulation information
boolean isComplex = analysisType == Analysis.ANALYSIS_AC;
int sweepCounter = sweepcnt;
for(;;) {
// get sweep info
String sweepName = "";
if (sweepcnt > 0) {
float sweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF before sweep data"); break; }
sweepName = TextUtils.formatDouble(sweepValue);
if (DEBUGCONDITIONS) System.out.println("READING SWEEP NUMBER: "+sweepValue);
// if there are more than 2 conditions, read extra sweep values
for(int i=2; i<cndcnt; i++) {
float anotherSweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF reading sweep header"); break; }
sweepName += "," + TextUtils.formatDouble(anotherSweepValue);
if (DEBUGCONDITIONS) System.out.println(" EXTRA SWEEP NUMBER: "+anotherSweepValue);
}
sweepName = ":"+sweepName;
}
for(;;) {
// get the first number, see if it terminates
float time = getHSpiceFloat(true);
if (eofReached) break;
// get a row of numbers
for(int k=0; k<numSignals; k++) {
if (isComplex) {
float realPart = getHSpiceFloat(false);
float imagPart = getHSpiceFloat(false);
/*
signals[k].addSample(time, new ComplexSample(realPart, imagPart));
*/
signals[k].addSample(time, new ScalarSample(realPart));
} else {
signals[k].addSample(time, new ScalarSample(getHSpiceFloat(false)));
}
if (eofReached) {
System.out.println("EOF in the middle of the data (at " + k + " out of " + numSignals +")");
break;
}
}
if (eofReached) { System.out.println("EOF before the end of the data"); break; }
}
sweepCounter--;
if (sweepCounter <= 0) break;
eofReached = false;
}
closeInput();
stopProgressDialog();
System.out.println("Done reading " + analysisType.toString() + " analysis");
}
|
private void readTRDCACFile(Stimuli sd, URL fileURL, List<PALine> paList, Analysis.AnalysisType analysisType)
throws IOException
{
if (openBinaryInput(fileURL)) return;
eofReached = false;
resetBinaryTRACDCReader();
AnalogAnalysis an = new AnalogAnalysis(sd, analysisType, false);
startProgressDialog("HSpice " + analysisType.toString() + " analysis", fileURL.getFile());
System.out.println("Reading HSpice " + analysisType.toString() + " analysis '" + fileURL.getFile() + "'");
// get number of nodes
int nodcnt = getHSpiceInt();
// get number of special items
int numnoi = getHSpiceInt();
// get number of conditions
int cndcnt = getHSpiceInt();
/*
* Although this isn't documented anywhere, it appears that the 4th
* number in the file is a multiplier for the first, which allows
* there to be more than 10000 nodes.
*/
StringBuffer line = new StringBuffer();
for(int j=0; j<4; j++) line.append((char)getByteFromFile());
int multiplier = TextUtils.atoi(line.toString(), 0, 10);
nodcnt += multiplier * 10000;
int numSignals = numnoi + nodcnt - 1;
if (numSignals <= 0)
{
System.out.println("Error reading " + fileURL.getFile());
closeInput();
stopProgressDialog();
return;
}
// get version number (known to work with 9007, 9601)
int version = getHSpiceInt();
if (version != 9007 && version != 9601)
System.out.println("Warning: may not be able to read HSpice files of type " + version);
// ignore the unused/title information (4+72 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// ignore the date/time information (16 characters)
line = new StringBuffer();
for(int j=0; j<16; j++) line.append((char)getByteFromFile());
// ignore the copywrite information (72 characters over line break)
line = new StringBuffer();
for(int j=0; j<72; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get number of sweeps
int sweepcnt = getHSpiceInt();
if (DEBUGCONDITIONS)
System.out.println("++++++++++++++++++++ VERSION="+version+" SWEEPCNT="+sweepcnt+" CNDCNT="+cndcnt+" NUMNOI="+numnoi+" MULTIPLIER="+multiplier);
if (cndcnt == 0) sweepcnt = 0;
// ignore the Monte Carlo information (76 characters over line break)
line = new StringBuffer();
for(int j=0; j<76; j++)
{
int k = getByteFromFile();
line.append((char)k);
if (!isTRACDCBinary && k == '\n') j--;
}
// get the type of each signal
String [] signalNames = new String[numSignals];
int [] signalTypes = new int[numSignals];
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(int j=0; j<8; j++)
{
int l = getByteFromFile();
line.append((char)l);
if (!isTRACDCBinary && l == '\n') j--;
}
if (k == 0) continue;
int l = k - nodcnt;
if (k < nodcnt) l = k + numnoi - 1;
String lineStr = line.toString().trim();
signalTypes[l] = TextUtils.atoi(lineStr, 0, 10);
}
boolean paMissingWarned = false;
for(int k=0; k<=numSignals; k++)
{
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ')
{
if (line.length() != 0) break;
// if name starts with blank, skip until non-blank
for(;;)
{
l = getByteFromFile();
if (l != ' ') break;
}
}
line.append((char)l);
if (version == 9007 && line.length() >= 16) break;
}
int j = line.length();
int l = (j+16) / 16 * 16 - 1;
if (version == 9007)
{
l = (j+15) / 16 * 16 - 1;
}
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (k == 0) continue;
// convert name if there is a colon in it
int startPos = 0;
int openPos = line.indexOf("(");
if (openPos >= 0) startPos = openPos+1;
for(j=startPos; j<line.length(); j++)
{
if (line.charAt(j) == ':') break;
if (!TextUtils.isDigit(line.charAt(j))) break;
}
if (j < line.length() && line.charAt(j) == ':')
{
l = TextUtils.atoi(line.toString().substring(startPos), 0, 10);
PALine foundPALine = null;
if (paList == null)
{
if (!paMissingWarned)
System.out.println("Warning: there should be a ." + paExtension + " file with extra signal names");
paMissingWarned = true;
} else
{
for(PALine paLine : paList)
{
if (paLine.number == l) { foundPALine = paLine; break; }
}
}
if (foundPALine != null)
{
StringBuffer newSB = new StringBuffer();
newSB.append(line.substring(0, startPos));
newSB.append(foundPALine.string);
newSB.append(line.substring(j+1));
line = newSB;
}
} else
{
if (line.indexOf(".") >= 0)
{
String fixedLine = removeLeadingX(line.toString());
line = new StringBuffer();
line.append(fixedLine);
}
}
// move parenthesis from the start to the last name
openPos = line.indexOf("(");
if (openPos >= 0)
{
String parenPrefix = line.substring(0, openPos+1);
int lastDot = line.lastIndexOf(".");
if (lastDot >= 0)
{
StringBuffer newSB = new StringBuffer();
if (parenPrefix.equalsIgnoreCase("v("))
{
// just ignore the V()
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(line.substring(lastDot+1, line.length()-1));
} else
{
// move the parenthetical wrapper to the last dotted piece
newSB.append(line.substring(openPos+1, lastDot+1));
newSB.append(parenPrefix);
newSB.append(line.substring(lastDot+1));
}
line = newSB;
} else if (parenPrefix.equalsIgnoreCase("v("))
{
StringBuffer newSB = new StringBuffer();
// just ignore the V()
newSB.append(line.substring(openPos+1, line.length()-1));
line = newSB;
}
}
if (k < nodcnt) l = k + numnoi - 1; else l = k - nodcnt;
signalNames[l] = line.toString();
}
// read (and ignore) condition information
for(int c=0; c<cndcnt; c++)
{
int j = 0;
line = new StringBuffer();
for(;;)
{
int l = getByteFromFile();
if (l == '\n') continue;
if (l == ' ') break;
line.append((char)l);
j++;
if (j >= 16) break;
}
int l = (j+15) / 16 * 16 - 1;
for(; j<l; j++)
{
int i = getByteFromFile();
if (!isTRACDCBinary && i == '\n') { j--; continue; }
}
if (DEBUGCONDITIONS)
System.out.println("CONDITION "+(c+1)+" IS "+line.toString());
}
// read the end-of-header marker
line = new StringBuffer();
if (!isTRACDCBinary)
{
// finish line, ensure the end-of-header
for(int j=0; ; j++)
{
int l = getByteFromFile();
if (l == '\n') break;
if (j < 4) line.append(l);
}
} else
{
// gather end-of-header string
for(int j=0; j<4; j++)
line.append((char)getByteFromFile());
}
if (!line.toString().equals("$&%#"))
{
System.out.println("HSpice header improperly terminated (got "+line.toString()+")");
closeInput();
stopProgressDialog();
return;
}
resetBinaryTRACDCReader();
// preprocess signal names to remove constant prefix (this code also occurs in VerilogOut.readVerilogFile)
String constantPrefix = null;
boolean hasPrefix = true;
for(int k=0; k<numSignals; k++)
{
String name = signalNames[k];
int dotPos = name.indexOf('.');
if (dotPos < 0) continue;
String prefix = name.substring(0, dotPos);
if (constantPrefix == null) constantPrefix = prefix;
if (!constantPrefix.equals(prefix)) { hasPrefix = false; break; }
}
if (!hasPrefix) constantPrefix = null; else {
String fileName = fileURL.getFile();
int pos = fileName.lastIndexOf(File.separatorChar);
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.lastIndexOf('/');
if (pos >= 0) fileName = fileName.substring(pos+1);
pos = fileName.indexOf('.');
if (pos >= 0) fileName = fileName.substring(0, pos);
if (fileName.equals(constantPrefix)) constantPrefix += "."; else
constantPrefix = null;
}
AnalogSignal[] signals = new AnalogSignal[numSignals];
for(int k=0; k<numSignals; k++) {
String name = signalNames[k];
if (constantPrefix != null &&
name.startsWith(constantPrefix))
name = name.substring(constantPrefix.length());
String context = null;
int lastDotPos = name.lastIndexOf('.');
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos+1);
}
signals[k] = new AnalogSignal(an, name, context);
}
// setup the simulation information
boolean isComplex = analysisType == Analysis.ANALYSIS_AC;
int sweepCounter = sweepcnt;
for(;;) {
// get sweep info
String sweepName = "";
if (sweepcnt > 0) {
float sweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF before sweep data"); break; }
sweepName = TextUtils.formatDouble(sweepValue);
if (DEBUGCONDITIONS) System.out.println("READING SWEEP NUMBER: "+sweepValue);
// if there are more than 2 conditions, read extra sweep values
for(int i=2; i<cndcnt; i++) {
float anotherSweepValue = getHSpiceFloat(false);
if (eofReached) { System.out.println("EOF reading sweep header"); break; }
sweepName += "," + TextUtils.formatDouble(anotherSweepValue);
if (DEBUGCONDITIONS) System.out.println(" EXTRA SWEEP NUMBER: "+anotherSweepValue);
}
sweepName = ":"+sweepName;
}
for(;;) {
// get the first number, see if it terminates
float time = getHSpiceFloat(true);
if (eofReached) break;
// get a row of numbers
for(int k=0; k<numSignals; k++) {
if (isComplex) {
float realPart = getHSpiceFloat(false);
float imagPart = getHSpiceFloat(false);
/*
signals[k].addSample(time, new ComplexSample(realPart, imagPart));
*/
signals[k].addSample(time, new ScalarSample(realPart));
} else {
if (signals[k].getSample(time)==null)
signals[k].addSample(time, new ScalarSample(getHSpiceFloat(false)));
}
if (eofReached) {
System.out.println("EOF in the middle of the data (at " + k + " out of " + numSignals +")");
break;
}
}
if (eofReached) { System.out.println("EOF before the end of the data"); break; }
}
sweepCounter--;
if (sweepCounter <= 0) break;
eofReached = false;
}
closeInput();
stopProgressDialog();
System.out.println("Done reading " + analysisType.toString() + " analysis");
}
|
diff --git a/openFaces/source/org/openfaces/component/validation/ValidatorPhaseListener.java b/openFaces/source/org/openfaces/component/validation/ValidatorPhaseListener.java
index 0de184a9f..d41b6993c 100644
--- a/openFaces/source/org/openfaces/component/validation/ValidatorPhaseListener.java
+++ b/openFaces/source/org/openfaces/component/validation/ValidatorPhaseListener.java
@@ -1,125 +1,125 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2010, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.component.validation;
import org.openfaces.org.json.JSONObject;
import org.openfaces.util.PhaseListenerBase;
import org.openfaces.util.RequestFacade;
import org.openfaces.util.ResponseFacade;
import org.openfaces.validator.AjaxSupportedConverter;
import javax.faces.FacesException;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
/**
* @author Ekaterina Shliakhovetskaya
*/
public class ValidatorPhaseListener extends PhaseListenerBase {
private static final String AJAX_VALIDATOR_REQUEST_HEADER = "teamdev_ajax_VALIDATOR";
private static final int BUFFER_SIZE = 10000;
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
public void afterPhase(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId() == PhaseId.RESTORE_VIEW) {
ValidationProcessor.resetVerifiableComponents(phaseEvent.getFacesContext());
}
}
public void beforePhase(PhaseEvent phaseEvent) {
if (checkPortletMultipleNotifications(phaseEvent, true))
return;
FacesContext context = phaseEvent.getFacesContext();
Object requestObj = context.getExternalContext().getRequest();
RequestFacade request = RequestFacade.getInstance(requestObj);
checkOurPhaseListenerInvokedOnce(phaseEvent);
if (isAjaxValidatorRequest(request)) {
try {
ResponseFacade response = ResponseFacade.getInstance(context.getExternalContext().getResponse());
processValidation(context, request, response);
} catch (IOException e) {
throw new FacesException(e);
}
}
}
private boolean isAjaxValidatorRequest(RequestFacade request) {
// for portlets: String browser = request.getProperty(...);
return request.getHeader(AJAX_VALIDATOR_REQUEST_HEADER) != null; // todo: getHeader can't be used on portlets - doesn't work in Liferay
}
private void processValidation(FacesContext context, RequestFacade request, ResponseFacade response) throws IOException {
Converter converter = null;
response.setContentType("text/plain");
Writer writer = response.getWriter();
InputStream input = request.getInputStream();
boolean isValid = true;
if (input != null) {
InputStreamReader reader = new InputStreamReader(input);
char[] target = new char[BUFFER_SIZE];
- int readed = reader.read(target);
- String params = new String(target, 0, readed);
+ int charsRead = reader.read(target);
+ String params = new String(target, 0, charsRead);
try {
JSONObject jParams = new JSONObject(params);
JSONObject jValidatorTransportObject = jParams.getJSONObject("params");
String jValue = jValidatorTransportObject.getString("value");
JSONObject jValidator = jValidatorTransportObject.getJSONObject("validator");
String javaClassName = jValidator.getString("javaClassName");
if (javaClassName != null) {
Object validator = Class.forName(javaClassName).newInstance();
if (validator instanceof AjaxSupportedConverter) {
converter = ((AjaxSupportedConverter) validator).getConverter(context, jValidator);
}
}
if (converter != null) {
try {
converter.getAsObject(context, new UIInput(), jValue);
} catch (RuntimeException e) {
isValid = false;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
reader.close();
}
writer.write(Boolean.toString(isValid));
writer.flush();
writer.close();
context.responseComplete();
}
}
| true | true |
private void processValidation(FacesContext context, RequestFacade request, ResponseFacade response) throws IOException {
Converter converter = null;
response.setContentType("text/plain");
Writer writer = response.getWriter();
InputStream input = request.getInputStream();
boolean isValid = true;
if (input != null) {
InputStreamReader reader = new InputStreamReader(input);
char[] target = new char[BUFFER_SIZE];
int readed = reader.read(target);
String params = new String(target, 0, readed);
try {
JSONObject jParams = new JSONObject(params);
JSONObject jValidatorTransportObject = jParams.getJSONObject("params");
String jValue = jValidatorTransportObject.getString("value");
JSONObject jValidator = jValidatorTransportObject.getJSONObject("validator");
String javaClassName = jValidator.getString("javaClassName");
if (javaClassName != null) {
Object validator = Class.forName(javaClassName).newInstance();
if (validator instanceof AjaxSupportedConverter) {
converter = ((AjaxSupportedConverter) validator).getConverter(context, jValidator);
}
}
if (converter != null) {
try {
converter.getAsObject(context, new UIInput(), jValue);
} catch (RuntimeException e) {
isValid = false;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
reader.close();
}
writer.write(Boolean.toString(isValid));
writer.flush();
writer.close();
context.responseComplete();
}
|
private void processValidation(FacesContext context, RequestFacade request, ResponseFacade response) throws IOException {
Converter converter = null;
response.setContentType("text/plain");
Writer writer = response.getWriter();
InputStream input = request.getInputStream();
boolean isValid = true;
if (input != null) {
InputStreamReader reader = new InputStreamReader(input);
char[] target = new char[BUFFER_SIZE];
int charsRead = reader.read(target);
String params = new String(target, 0, charsRead);
try {
JSONObject jParams = new JSONObject(params);
JSONObject jValidatorTransportObject = jParams.getJSONObject("params");
String jValue = jValidatorTransportObject.getString("value");
JSONObject jValidator = jValidatorTransportObject.getJSONObject("validator");
String javaClassName = jValidator.getString("javaClassName");
if (javaClassName != null) {
Object validator = Class.forName(javaClassName).newInstance();
if (validator instanceof AjaxSupportedConverter) {
converter = ((AjaxSupportedConverter) validator).getConverter(context, jValidator);
}
}
if (converter != null) {
try {
converter.getAsObject(context, new UIInput(), jValue);
} catch (RuntimeException e) {
isValid = false;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
reader.close();
}
writer.write(Boolean.toString(isValid));
writer.flush();
writer.close();
context.responseComplete();
}
|
diff --git a/MULE/src/Renderer.java b/MULE/src/Renderer.java
index dbff824..748ad30 100644
--- a/MULE/src/Renderer.java
+++ b/MULE/src/Renderer.java
@@ -1,1277 +1,1276 @@
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.DefaultCaret;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.BorderFactory;
import java.util.concurrent.locks.*;
import java.util.ArrayList;
import java.util.Date;
public class Renderer {
private JFrame frame;
private boolean waiting;
private String[] states; // keeps track of the state of the GUI
private ReentrantLock lock;
protected static final int WIDTH = 9;
protected static final int HEIGHT = 5;
protected static final int TILE_SIZE = 100;
private JButton[] buttons = new JButton[WIDTH + HEIGHT];
private Timer timer;
private boolean isSelectedButtonCreated = false;
private long timeWhenTimerSet;
private long pauseTime;
private int num;
private boolean paused;
/**
* Renderer handles all graphics related actions for game.
*/
public Renderer() {
frame = new JFrame("M.U.L.E.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setMinimumSize(new Dimension(950, 770));
frame.setPreferredSize(new Dimension(950, 770));
frame.setVisible(true);
waiting = true;
lock = new ReentrantLock();
frame.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
timer = createTimer(50000);
paused = false;
}
public String[] drawIntroScreen() {
// declare initial variables
String action = "";
states = new String[1];
states[0] = "new";
ImagePanel panel = new ImagePanel("/media/startscreen.png");
panel.setPreferredSize(new Dimension(950, 700));
panel.setLayout(null);
ImagePanel menuPanel = new ImagePanel("/media/bss.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(menuPanel);
changePanel(frame, panels);
// add buttons
final JButton quitButton = addButtonToPanel(menuPanel, 11, 7, 171, 40, 0, "quit");
addHoverIcon(quitButton, "/media/hoverbuttons/quithover.png");
final JButton loadButton = addButtonToPanel(menuPanel, 590, 7, 171, 40, 0, "load");
addHoverIcon(loadButton, "/media/hoverbuttons/loadhover.png");
JButton newButton = addButtonToPanel(menuPanel, 771, 7, 171, 40, 0, "new");
//addHoverIcon(loadButton, "/media/hoverbuttons/newhover.png");
blockForInput();
exitSafely();
return states;
}
// States[0] - Action to perform: {"back", "okay"}
// States[1] - Difficulty: {"1", "2", "3"}
// States[2] - Number of Players: {"1", "2", "3", "4", "5"}
public String[] drawSetupScreen(int numPlayers, int difficulty) {
// declare initial variables
String action = "";
states = new String[3];
states[0] = "okay";
states[1] = "1";
states[2] = "1";
String difficultyValue = getDifficultyValueString(difficulty);
ImagePanel panel = new ImagePanel("/media/gamesetup.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
ImagePanel playerBox1 = new ImagePanel("/media/p00.png");
playerBox1.setPreferredSize(new Dimension(160, 175));
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
playerPanel.add(playerBox1);
for (int i = 1; i < numPlayers+1; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+"0.png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
for (int i = numPlayers+1; i < 6; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+".png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
ImagePanel menuPanel = new ImagePanel("/media/bp0.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
// add buttons
JButton backButton = addButtonToPanel(menuPanel, 11, 7, 171, 40, 0, "back");
JButton okayButton = addButtonToPanel(menuPanel, 771, 7, 171, 40, 0, "okay");
JButton easyButton = addButtonToPanel(panel, 160, 164, 77, 40, 1, "1");
JButton mediumButton = addButtonToPanel(panel, 407, 164, 137, 38, 1, "2");
JButton hardButton = addButtonToPanel(panel, 715, 164, 78, 38, 1, "3");
JButton onePlayer = addButtonToPanel(panel, 185, 404, 24, 40, 2, "1");
JButton twoPlayer = addButtonToPanel(panel, 325, 404, 24, 40, 2, "2");
JButton threePlayer = addButtonToPanel(panel, 465, 404, 24, 40, 2, "3");
JButton fourPlayer = addButtonToPanel(panel, 605, 404, 24, 40, 2, "4");
JButton fivePlayer = addButtonToPanel(panel, 745, 404, 24, 40, 2, "5");
blockForSetupScreen(panel, playerBox1, 170, 150, 280, numPlayers, difficultyValue, playerPanel);
exitSafely();
return states;
}
// States[0] - Action to perform: {"new", "load", "quit"}
// States[1] - Map Number: {"1", "2", "3", "4", "5"}
public String[] drawMapScreen(int numPlayers, int difficulty) {
// declare initial variables
String action = "";
states = new String[2];
states[0] = "okay";
states[1] = "1";
this.num = numPlayers;
String difficultyValue = getDifficultyValueString(difficulty);
ImagePanel panel = new ImagePanel("/media/mapselection.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
ImagePanel playerBox1 = new ImagePanel("/media/p00.png");
playerBox1.setPreferredSize(new Dimension(160, 175));
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
playerPanel.add(playerBox1);
for (int i = 1; i < numPlayers+1; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+"0.png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
for (int i = numPlayers+1; i < 6; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+".png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
ImagePanel menuPanel = new ImagePanel("/media/bp0.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
// add buttons
JButton backButton = addButtonToPanel(menuPanel, 11, 7, 170, 40, 0, "back");
JButton okayButton = addButtonToPanel(menuPanel, 770, 7, 170, 40, 0, "okay");
JButton map1Button = addButtonToPanel(panel, 110, 162, 224, 126, 1, "1");
JButton map2Button = addButtonToPanel(panel, 365, 162, 224, 126, 1, "2");
JButton map3Button = addButtonToPanel(panel, 617, 162, 224, 126, 1, "3");
JButton map4Button = addButtonToPanel(panel, 235, 317, 224, 126, 1, "4");
JButton map5Button = addButtonToPanel(panel, 490, 317, 224, 126, 1, "5");
blockForMapScreen(panel, playerBox1, difficultyValue);
exitSafely();
return states;
}
// REFACTOR THIS BIT TO MAKE PANELS MORE STATIC -ALex
// States[0] - Action to perform: {"new", "load", "quit"}
// States[1] - Race: {"human", "elephant", "squirrel", "frog", "cat"}
// States[2] - Player Name
// States[3] - Color: {"red", "blue", "pink", "green", "orange"}
public String[] drawCharacterScreen(ArrayList<Player> players, int difficulty, Map map, int size) {
// declare initial variables
String action = "";
states = new String[4];
states[0] = "okay";
states[1] = "human";
states[2] = "default";
states[3] = "red";
String difficultyValue = getDifficultyValueString(difficulty);
ImagePanel panel = new ImagePanel("/media/playerselection.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
ImagePanel playerBox1 = new ImagePanel("/media/p00.png");
playerBox1.setPreferredSize(new Dimension(160, 175));
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
playerPanel.add(playerBox1);
for (int i = 1; i < num+1; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+"0.png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
for (int i = num+1; i < 6; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+".png");
playerBox.setPreferredSize(new Dimension(158, 175));
playerPanel.add(playerBox);
}
for (int i = 0; i < players.size(); i++) {
drawPlayerCharacter(players.get(i), i, playerPanel);
}
ImagePanel menuPanel = new ImagePanel("/media/bp0.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
// add buttons
JButton backButton = addButtonToPanel(menuPanel, 11, 7, 170, 40, 0, "back");
JButton okayButton = addButtonToPanel(menuPanel, 771, 7, 170, 40, 0, "okay");
JButton humanButton = addButtonToPanel(panel, 75, 78, 133, 115, 1, "human");
JButton elephantButton = addButtonToPanel(panel, 232, 78, 133, 115, 1, "elephant");
JButton squirrelButton = addButtonToPanel(panel, 413, 78, 123, 115, 1, "squirrel");
JButton frogButton = addButtonToPanel(panel, 593, 78, 98, 115, 1, "frog");
JButton catButton = addButtonToPanel(panel, 763, 78, 98, 115, 1, "cat");
JButton redButton = addButtonToPanel(panel, 92, 250, 130, 200, 3, "red");
JButton blueButton = addButtonToPanel(panel, 260, 250, 130, 200, 3, "blue");
JButton pinkButton = addButtonToPanel(panel, 427, 250, 130, 200, 3, "pink");
JButton greenButton = addButtonToPanel(panel, 587, 250, 130, 200, 3, "green");
JButton orangeButton = addButtonToPanel(panel, 750, 250, 130, 200, 3, "orange");
JTextField nameBox = addTextToPanel(menuPanel, 420, 6, 225, 38); //480
blockForInputCharacter(panel, playerBox1, difficultyValue, map, playerPanel, players);
exitSafely();
states[2] = nameBox.getText();
return states;
}
public String[] drawTownScreen(ArrayList<Player> players, int currPlayer, Store store, int numPlayers, int round) {
states = new String[2];
ImagePanel panel = new ImagePanel("/media/town.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(null);
drawGameStatus(players, playerPanel, currPlayer, store, numPlayers, round);
ImagePanel menuPanel = new ImagePanel("/media/bp1.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
// buttons
addButtonToPanel(panel, 60, 60, 200, 400, 0, "assay");
addButtonToPanel(panel, 260, 60, 250, 400, 0, "store");
addButtonToPanel(panel, 510, 60, 210, 400, 0, "land office");
addButtonToPanel(panel, 720, 60, 200, 400, 0, "pub");
addButtonToPanel(panel, 81, 456, 100, 61, 0, "back");
addButtonToPanel(menuPanel, 783, 7, 40, 40, 0, "stop");
addButtonToPanel(menuPanel, 837, 7, 40, 40, 0, "pause");
addButtonToPanel(menuPanel, 893, 7, 40, 40, 0, "skip");
blockForInputMain(menuPanel);
exitSafely();
states[1] = "" + timer.getDelay();
return states;
}
// state[0] = {"quit", "switchScreen", "food", "energy", "smithore", "crystite", "foodMule", "energyMule", "smithoreMule", "crystiteMule"}
// state[1] = quantityFood
// state[2] = quantityEnergy
// state[3] = quantitySmithore
// state[4] = quantityCrystite
public String[] drawStoreScreen(ArrayList<Player> players, int currPlayer, String transactionType, String[] quantities,
Store store, int numPlayers, int round) {
// initialize the states
states = new String[5];
states[0] = "quit";
states[1] = quantities[0];
states[2] = quantities[1];
states[3] = quantities[2];
states[4] = quantities[3];
ImagePanel panel = new ImagePanel("/media/storecomponents/store" + transactionType + ".png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(null);
drawGameStatus(players, playerPanel, currPlayer, store, numPlayers, round);
ImagePanel menuPanel = new ImagePanel("/media/bp1.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
// buttons
addButtonToPanel(panel, 40, 455, 98, 58, 0, "quit");
addButtonToPanel(panel, 166, 455, 98, 58, 0, "switchScreen");
addButtonToPanel(panel, 471, 135, 42, 25, 0, "food");
addButtonToPanel(panel, 471, 220, 42, 25, 0, "energy");
addButtonToPanel(panel, 471, 305, 42, 25, 0, "smithore");
addButtonToPanel(panel, 471, 391, 42, 25, 0, "crystite");
addButtonToPanel(panel, 693, 161, 42, 25, 0, "foodMule");
addButtonToPanel(panel, 693, 257, 42, 25, 0, "energyMule");
addButtonToPanel(panel, 853, 161, 42, 25, 0, "smithoreMule");
addButtonToPanel(panel, 853, 257, 42, 25, 0, "crystiteMule");
addButtonToPanel(panel, 290, 117, 22, 18, 1, "+");
addButtonToPanel(panel, 290, 157, 22, 18, 1, "-");
addButtonToPanel(panel, 290, 202, 22, 18, 2, "+");
addButtonToPanel(panel, 290, 242, 22, 18, 2, "-");
addButtonToPanel(panel, 290, 288, 22, 18, 3, "+");
addButtonToPanel(panel, 290, 328, 22, 18, 3, "-");
addButtonToPanel(panel, 290, 373, 22, 18, 4, "+");
addButtonToPanel(panel, 290, 413, 22, 18, 4, "-");
addButtonToPanel(menuPanel, 783, 7, 40, 40, 0, "stop");
addButtonToPanel(menuPanel, 837, 7, 40, 40, 0, "pause");
addButtonToPanel(menuPanel, 893, 7, 40, 40, 0, "skip");
blockForInputMain(menuPanel);
exitSafely();
return states;
}
public String[] drawMenuScreen(ArrayList<Player> players, int currPlayer, Store store, int numPlayers, int round) {
states = new String[2];
ImagePanel panel = new ImagePanel("/media/menu.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(null);
drawGameStatus(players, playerPanel, currPlayer, store, numPlayers, round);
ImagePanel menuPanel = new ImagePanel("/media/bp.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
addButtonToPanel(panel, 390, 166, 170, 40, 0, "resume");
addButtonToPanel(panel, 390, 242, 170, 40, 0, "save");
addButtonToPanel(panel, 390, 316, 170, 40, 0, "load");
addButtonToPanel(panel, 390, 390, 170, 40, 0, "quit");
blockForInputMain(menuPanel);
exitSafely();
return states;
}
public String[] drawLandOfficeScreen(ArrayList<Player> players, int currPlayer, Store store, int numPlayers, int round) {
states = new String[2];
ImagePanel panel = new ImagePanel("/media/landoffice.png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(null);
drawGameStatus(players, playerPanel, currPlayer, store, numPlayers, round);
ImagePanel menuPanel = new ImagePanel("/media/bp1.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
addButtonToPanel(panel, 126, 198, 166, 35, 0, "buy");
addButtonToPanel(panel, 126, 283, 166, 35, 0, "sell");
addButtonToPanel(panel, 81, 456, 100, 61, 0, "back");
blockForInputMain(menuPanel);
exitSafely();
return states;
}
// State[0] = {"town", "time"}
// State[1] = time left on timer
public String[] drawMainGameScreen(Map map, ArrayList<Player> players, int currPlayer, Store store, int numPlayers, int round, String text) {
states = new String[2];
ImagePanel panel = new ImagePanel("/media/map"+map.getMapNum()+".png");
panel.setPreferredSize(new Dimension(950, 525));
panel.setLayout(null);
JPanel playerPanel = new JPanel();
playerPanel.setPreferredSize(new Dimension(950, 175));
playerPanel.setLayout(null);
drawPlayerFlags(map, panel);
drawPlayerMules(map, panel);
drawTerrain(map, panel);
drawGameStatus(players, playerPanel, currPlayer, store, numPlayers, round);
ImagePanel menuPanel = new ImagePanel("/media/bp1.png");
menuPanel.setPreferredSize(new Dimension(950, 50));
menuPanel.setLayout(null);
ArrayList<JPanel> panels = new ArrayList<JPanel>();
panels.add(panel);
panels.add(playerPanel);
panels.add(menuPanel);
changePanel(frame, panels);
JButton[] buttons = new JButton[Map.WIDTH * Map.HEIGHT];
for (int i = 0; i < Map.HEIGHT; i++) {
for (int j = 0; j < Map.WIDTH; j++) {
buttons[i * Map.WIDTH + j] = addButtonToPanel(panel, 25 + j * 100, 25 + i * 100, 100, 100, 0, "" + (i * Map.WIDTH + j));
}
}
addButtonToPanel(menuPanel, 783, 7, 40, 40, 0, "stop");
addButtonToPanel(menuPanel, 837, 7, 40, 40, 0, "pause");
addButtonToPanel(menuPanel, 893, 7, 40, 40, 0, "skip");
drawStatusText(menuPanel, text);
blockForInputMain(menuPanel);
exitSafely();
states[1] = "" + timer.getDelay();
return states;
}
public void drawLoadScreen(LoadScreenModel model) {
return;
}
// helper methods
private void changePanel(JFrame frame, ArrayList<JPanel> panels) {
frame.getContentPane().removeAll();
for (JPanel panel : panels) {
frame.add(panel);
}
frame.pack();
frame.repaint();
return;
}
private void blockForInput() {
// wait for a button to be clicked
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
}
private void blockForMapScreen(JPanel panel, ImagePanel infoPanel, String difficultyValue){
try { Thread.sleep(100); } catch (Exception e) {}
JTextField difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
JLabel map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 1+ ".png");
JLabel mapArrow = addLabelToPanel(panel, 199, 289, 45, 24, "/media/uparrow.png");
panel.repaint();
infoPanel.repaint();
String oldState = states[1];
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
if (!oldState.equals(states[1])) {
infoPanel.remove(difficultyText);
difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
if(states[1].equals("1")){
infoPanel.remove(map);
map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 1+ ".png");
panel.remove(mapArrow);
mapArrow = addLabelToPanel(panel, 199, 289, 45, 24, "/media/uparrow.png");
}
if(states[1].equals("2")){
infoPanel.remove(map);
map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 2+ ".png");
panel.remove(mapArrow);
mapArrow = addLabelToPanel(panel, 453, 289, 45, 24, "/media/uparrow.png");
}
if(states[1].equals("3")){
infoPanel.remove(map);
map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 3+ ".png");
panel.remove(mapArrow);
mapArrow = addLabelToPanel(panel, 705, 289, 45, 24, "/media/uparrow.png");
}
if(states[1].equals("4")){
infoPanel.remove(map);
map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 4+ ".png");
panel.remove(mapArrow);
mapArrow = addLabelToPanel(panel, 326, 444, 45, 24, "/media/uparrow.png");
}
if(states[1].equals("5")){
infoPanel.remove(map);
map = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ 5+ ".png");
panel.remove(mapArrow);
mapArrow = addLabelToPanel(panel, 580, 444, 45, 24, "/media/uparrow.png");
}
panel.repaint();
infoPanel.repaint();
oldState = states[1];
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
}
private void blockForSetupScreen(JPanel panel, ImagePanel infoPanel, int x, int y, int xMargin, int numPlayers, String difficultyValue, JPanel playerPanel){
try { Thread.sleep(100); } catch (Exception e) {}
JLabel difficultyArrow = addLabelToPanel(panel, (Integer.parseInt(states[1])-1)*xMargin + x, y, 804, 200, "/media/uparrow.png");
JLabel playerArrow = addLabelToPanel(panel, (Integer.parseInt(states[2])-1)*150 + x, 390, 804, 200, "/media/uparrow.png");
JTextField difficultyText = drawDifficulty(infoPanel, getDifficultyValueString(Integer.parseInt(states[1])), 0, 125, 162, 25);
panel.repaint();
infoPanel.repaint();
playerPanel.repaint();
String oldState = states[1];
String oldState2 = states[2];
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
if (!oldState.equals(states[1])) {
panel.remove(difficultyArrow);
difficultyArrow = addLabelToPanel(panel, (Integer.parseInt(states[1])-1)*xMargin + x , y, 804, 200, "/media/uparrow.png");
infoPanel.remove(difficultyText);
difficultyText = drawDifficulty(infoPanel, getDifficultyValueString(Integer.parseInt(states[1])), 0, 125, 162, 25);
infoPanel.repaint();
panel.repaint();
oldState = states[1];
}
if (!oldState2.equals(states[2])) {
panel.remove(playerArrow);
playerArrow = addLabelToPanel(panel, (Integer.parseInt(states[2])-1)*140 + x , 390, 804, 200, "/media/uparrow.png");
for (int i = 1; i < Integer.parseInt(states[2])+1; i++) {
playerPanel.remove(i);
JLabel playerBox = addLabelToPanel(playerPanel, i*158 , 0, 158, 175, "/media/p"+i+"0.png");
}
for (int i = Integer.parseInt(states[2])+1; i < 6; i++) {
JLabel playerBox = addLabelToPanel(playerPanel, i*158 , 0, 158, 175, "/media/p"+i+".png");
}
playerPanel.repaint();
panel.repaint();
oldState2 = states[2];
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
}
private JLabel blockForInputCharacter(JPanel panel, ImagePanel infoPanel, String difficultyValue, Map map, JPanel playerPanel, ArrayList<Player> players) {
try { Thread.sleep(100); } catch (Exception e) {}
JLabel charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
JLabel colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
JLabel colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
- System.out.println("pLAYER SIZE " +players.size());
JTextField difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
JLabel map1 = addLabelToPanel(infoPanel, 21 , 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
JLabel photo = addLabelToPanel(playerPanel, 200 + (players.size()*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
panel.repaint();
playerPanel.repaint();
String oldState = states[1];
System.out.println(states[2]);
String oldState2 = states[3];
int currentPlayer = players.size();
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
if (!oldState.equals(states[1])){
panel.remove(colors);
colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
infoPanel.remove(map1);
map1 = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
infoPanel.remove(difficultyText);
difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
if(states[1].equals("human")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("elephant")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 275, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("squirrel")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 450, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("frog")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 619, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("cat")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 787, 210, 45, 24, "/media/uparrow.png");
}
infoPanel.repaint();
panel.repaint();
oldState = states[1];
}
if (!oldState2.equals(states[3])) {
playerPanel.remove(photo);
photo = addLabelToPanel(playerPanel, 200 + (currentPlayer*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
if(states[3].equals("red")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("blue")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 275, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("pink")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 450, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("green")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 619, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("orange")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 787, 482, 45, 24, "/media/uparrow.png");
}
panel.repaint();
playerPanel.repaint();
oldState2 = states[3];
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
return colors;
}
private void blockForInputMain(JPanel panel) {
Date date = new Date();
long currentTime = date.getTime();
int timerNum = (int)(((currentTime - timeWhenTimerSet) / 1000) / 7);
int oldTimerNum = timerNum;
JLabel timerImage = addLabelToPanel(panel, 11, 4, 41, 41, "/media/t" + timerNum + ".png");
panel.repaint();
boolean waitingSafe = true;
while (waitingSafe) {
date = new Date();
currentTime = date.getTime();
timerNum = (int)(((currentTime - timeWhenTimerSet) / 1000) / 7);
if (oldTimerNum != timerNum && !paused) {
try {
panel.remove(timerImage);
}
catch (NullPointerException e) {
}
timerImage = addLabelToPanel(panel, 11, 4, 41, 41, "/media/t" + timerNum + ".png");
panel.repaint();
oldTimerNum = timerNum;
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
}
private void exitSafely() {
try {
lock.lock();
waiting = true;
}
finally {
lock.unlock();
}
}
private JButton addButtonToPanel(JPanel panel, int x, int y, int width, int height,
final int stateNum, final String stateText) {
final JButton button = new JButton();
button.setBounds(x, y, width, height);
panel.add(button);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (stateText.equals("+")) {
states[stateNum] = "" + (Integer.parseInt(states[stateNum]) + 1);
}
else if (stateText.equals("-")) {
states[stateNum] = "" + (Integer.parseInt(states[stateNum]) - 1);
if (states[stateNum].equals("-1")) {
states[stateNum] = "0";
}
}
else {
states[stateNum] = stateText; // set the new state
}
System.out.println(stateNum + " set to: " + stateText);
if (stateNum == 0) {
try {
lock.lock();
waiting = false;
}
finally {
lock.unlock();
}
}
}
});
///////
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
return button;
}
private Timer createTimer(int time) {
ActionListener timerListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
states[0] = "time";
try {
lock.lock();
waiting = false;
}
finally {
lock.unlock();
}
}
};
Timer timer = new Timer(time, timerListener);
return timer;
}
public void pauseTimer() {
if (paused)
return;
Date date = new Date();
pauseTime = date.getTime();
timer.stop();
paused = true;
}
public void unpauseTimer() {
if (!paused)
return;
Date date = new Date();
long timePaused = (date.getTime() - pauseTime);
pauseTime = 0;
timeWhenTimerSet += timePaused;
timer.start();
paused = false;
}
public void stopTimer() {
timer.stop();
}
public void startTimer(int time) {
Date date = new Date();
timeWhenTimerSet = date.getTime();
timer.setDelay(time);
timer.start();
}
public void restartTimer(int time) {
Date date = new Date();
timeWhenTimerSet = date.getTime();
timer.setDelay(time);
timer.restart();
}
public int getElapsedTime() {
Date date = new Date();
return (int)(date.getTime() - timeWhenTimerSet);
}
private JTextField addTextToPanel(JPanel panel, int x, int y, int width, int height) {
final JTextField text = new JTextField("Enter Name");
text.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
text.setText("");
}
});
text.setBounds(x, y, width, height);
DefaultCaret c = (DefaultCaret)text.getCaret();
c.setVisible(true);
c.setDot(0);
text.setFont(new Font("Candara", Font.PLAIN, 30));
text.setHorizontalAlignment(JTextField.LEFT);
text.setForeground(Color.WHITE);
text.setBackground(new Color(87, 51, 4));
text.setOpaque(false);
text.setCaretColor(Color.WHITE);
text.setBorder(javax.swing.BorderFactory.createEmptyBorder());
panel.add(text);
return text;
}
private JLabel addLabelToPanel(JPanel panel, int x, int y, int width, int height, String image) {
BufferedImage img;
try {
img = ImageIO.read(getClass().getResourceAsStream(image));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function addLabelToPanel");
return null;
}
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel();
label.setIcon(icon);
label.setBounds(x, y, width, height);
panel.add(label, 0);
return label;
}
private void drawGameStatus(ArrayList<Player> players, JPanel panel, int currPlayer, Store store, int numPlayers, int round) {
System.out.println("Size: " + players.size());
String output;
for (int i = 0; i < players.size(); i++) {
drawPlayerStatus(players.get(i), i, panel);
drawStoreStatus(store, panel);
}
if(round < 10){
output = "0" + round;
}
else{
output = "" + round;
}
JLabel roundLabel = new JLabel(output);
roundLabel.setBounds(87, 127, 18, 18);
panel.add(roundLabel);
if (currPlayer >= 0) {
// current player color
String colorPrefix = players.get(currPlayer).getColor().substring(0, 1);
BufferedImage colorImg;
try {
colorImg = ImageIO.read(getClass().getResourceAsStream("/media/circ" + colorPrefix + ".png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function drawGameStatus");
return;
}
JLabel colorLabel = new JLabel();
ImageIcon colorIcon = new ImageIcon(colorImg);
colorLabel.setIcon(colorIcon);
colorLabel.setBounds(122, 128, 18, 18);
panel.add(colorLabel);
}
// create boxes for players
for (int i = 0; i < numPlayers+1; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" + i + "1.png");
if (i == 0) {
playerBox.setBounds(0, 0, 160, 175);
}
else {
playerBox.setBounds(160 * i - (i - 1) * 2, 0, 158, 175);
}
panel.add(playerBox);
}
for (int i = numPlayers+1; i < 6; i++) {
ImagePanel playerBox = new ImagePanel("/media/p" +i+".png");
playerBox.setBounds(160 * i - (i - 1) * 2, 0, 158, 175);
panel.add(playerBox);
}
}
private void drawStoreStatus(Store store, JPanel panel){
int xBase = 0;
int yBase = 30;
//food label
JLabel foodLabel = new JLabel("" + store.getFoodQuantity());
foodLabel.setBounds(45, 53, 100, 20);
panel.add(foodLabel);
//energy label
JLabel energyLabel = new JLabel("" + store.getEnergyQuantity());
energyLabel.setBounds(103, 53, 100, 20);
panel.add(energyLabel);
//smithore label
JLabel smithoreLabel = new JLabel("" + store.getSmithoreQuantity());
smithoreLabel.setBounds(45, 88, 100, 20);
panel.add(smithoreLabel);
//crystite label
JLabel crystiteLabel = new JLabel("" + store.getCrystiteQuantity());
crystiteLabel.setBounds(103, 88, 100, 20);
panel.add(crystiteLabel);
//mule label
JLabel muleLabel = new JLabel("" + store.getMulesQuantity());
muleLabel.setBounds(45, 125, 100, 20);
panel.add(muleLabel);
}
private void drawPlayerCharacter(Player player, int number, JPanel playerPanel){
int xBase = 0;
int yBase = 30;
// player name label
JLabel playerLabel = new JLabel(player.getName());
playerLabel.setBounds((xBase + 158 * (number + 1)) + 30, 30 , 100, 20);
playerPanel.add(playerLabel);
}
private void drawPlayerStatus(Player player, int number, JPanel panel) {
int xBase = 0;
int yBase = 30;
// player name label
JLabel playerLabel = new JLabel(player.getName());
playerLabel.setBounds((xBase + 158 * (number + 1)) + 30, yBase, 100, 20);
panel.add(playerLabel);
// food label
JLabel foodLabel = new JLabel("" + player.getFood());
foodLabel.setBounds((xBase + 158 * (number + 1)) + 45, yBase + 23, 100, 20);
panel.add(foodLabel);
// energy label
JLabel energyLabel = new JLabel("" + player.getEnergy());
energyLabel.setBounds((xBase + 158 * (number + 1)) + 105, yBase + 23, 100, 20);
panel.add(energyLabel);
// smithore label
JLabel smithoreLabel = new JLabel("" + player.getSmithore());
smithoreLabel.setBounds((xBase + 158 * (number + 1)) + 45, yBase + 58, 100, 20);
panel.add(smithoreLabel);
// crystite label
JLabel muleLabel = new JLabel("" + player.getCrystite());
muleLabel.setBounds((xBase + 158 * (number + 1)) + 107, yBase + 58, 100, 20);
panel.add(muleLabel);
// money label
JLabel moneyLabel = new JLabel("" + player.getMoney());
moneyLabel.setBounds((xBase + 158 * (number + 1) + 45), yBase + 95, 100, 20);
panel.add(moneyLabel);
// color label
String colorPrefix = player.getColor().substring(0, 1);
BufferedImage colorImg;
try {
colorImg = ImageIO.read(getClass().getResourceAsStream("/media/circ" + colorPrefix + ".png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function drawPlayerStatus");
return;
}
JLabel colorLabel = new JLabel();
ImageIcon colorIcon = new ImageIcon(colorImg);
colorLabel.setIcon(colorIcon);
colorLabel.setBounds((xBase + 158 * (number + 1) + 124), yBase + 98, 18, 18);
panel.add(colorLabel);
}
private void drawPlayerFlags(Map map, JPanel panel) {
for (int i = 0; i < Map.HEIGHT; i++) {
for (int j = 0; j < Map.WIDTH; j++) {
Player owner = map.getOwnerOfTile(i * Map.WIDTH + j);
if (owner != null) {
drawPlayerFlag(i, j, owner, panel);
}
}
}
}
private void drawPlayerMules(Map map, JPanel panel) {
for (int i = 0; i < Map.HEIGHT; i++) {
for (int j = 0; j < Map.WIDTH; j++) {
Tile tile = map.getTiles()[i * Map.WIDTH + j];
if (tile != null && map.getTiles()[i * Map.WIDTH + j].hasMule()) {
drawPlayerMule(i, j, tile, panel);
System.out.println("Drawing mule at " + i + ", " + j);
}
}
}
}
private void drawTerrain(Map map, JPanel panel) {
for (int i = 0; i < Map.HEIGHT; i++) {
for (int j = 0; j < Map.WIDTH; j++) {
String type = map.getTileType(i * Map.WIDTH + j);
if (type.length() == 9 && type.substring(0, 8).equals("mountain"))
{
drawMountain(i, j, type.substring(8, 9), panel);
}
}
}
}
private JTextField drawDifficulty(JPanel panel, String textString, int x, int y, int width, int height) {
JTextField text = new JTextField(textString);
text.setBounds(x, y, width, height);
text.setFont(new Font("Candara", Font.PLAIN, 20));
text.setHorizontalAlignment(JTextField.CENTER);
text.setForeground(Color.BLACK);
text.setBackground(new Color(87, 51, 4));
text.setOpaque(false);
text.setBorder(javax.swing.BorderFactory.createEmptyBorder());
panel.add(text);
panel.repaint();
return text;
}
public JTextField drawStatusText(JPanel panel, String textString) {
if(panel == null){
panel = new ImagePanel("/media/bp1.png");
panel.setPreferredSize(new Dimension(950, 50));
panel.setLayout(null);
}
if (textString == null) {
return null;
}
System.out.println("Displaying: " + textString);
JTextField text = new JTextField(textString);
text.setBounds(60, 6, 600, 38);
text.setFont(new Font("Candara", Font.PLAIN, 12));
text.setHorizontalAlignment(JTextField.LEFT);
text.setForeground(Color.WHITE);
text.setBackground(new Color(87, 51, 4));
text.setOpaque(false);
text.setBorder(javax.swing.BorderFactory.createEmptyBorder());
text.setCaretColor(Color.WHITE);
panel.add(text);
panel.repaint();
return text;
}
private void drawPlayerFlag(int row, int column, Player player, JPanel panel) {
System.out.println("Drawing at location " + row + ", " + column);
BufferedImage flagImg;
String colorPrefix = player.getColor().substring(0, 1);
try {
flagImg = ImageIO.read(getClass().getResourceAsStream("/media/flag" + colorPrefix + ".png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function drawPlayerFlag");
return;
}
JLabel flagLabel = new JLabel();
ImageIcon flagIcon = new ImageIcon(flagImg);
flagLabel.setIcon(flagIcon);
flagLabel.setBounds(25 + column * 100, 25 + row * 100, 100, 100);
panel.add(flagLabel);
}
private void drawPlayerMule(int row, int column, Tile tile, JPanel panel) {
System.out.println("Drawing at location " + row + ", " + column);
BufferedImage muleImg;
String mulePrefix = tile.getMuleType().substring(0, 1);
mulePrefix = mulePrefix.toUpperCase();
try {
muleImg = ImageIO.read(getClass().getResourceAsStream("/media/storecomponents/mule" + mulePrefix + ".png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function drawPlayerMule");
System.out.println("mulePrefix: " + mulePrefix);
return;
}
JLabel muleLabel = new JLabel();
ImageIcon muleIcon = new ImageIcon(muleImg);
muleLabel.setIcon(muleIcon);
muleLabel.setBounds(25 + column * 100, 25 + row * 100, 100, 100);
panel.add(muleLabel);
}
private void drawMountain(int row, int column, String type, JPanel panel) {
BufferedImage mountImg;
try {
mountImg = ImageIO.read(getClass().getResourceAsStream("/media/mount" + type + ".png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function drawMountain");
return;
}
JLabel mountLabel = new JLabel();
ImageIcon mountIcon = new ImageIcon(mountImg);
mountLabel.setIcon(mountIcon);
mountLabel.setBounds(25 + column * 100, 25 + row * 100, 100, 100);
panel.add(mountLabel);
}
private String getDifficultyValueString(int num){
String returnString = "";
if (num == 1){
returnString = "Easy";
}
if (num == 2){
returnString = "Medium";
}
if (num == 3){
returnString = "Hard";
}
return returnString;
}
private void addHoverIcon(final JButton button, String image) {
BufferedImage img;
BufferedImage defaultImg;
try {
img = ImageIO.read(getClass().getResourceAsStream(image));
defaultImg = ImageIO.read(getClass().getResourceAsStream("/media/trans.png"));
}
catch (Exception e) {
System.out.println("Caught: " + e + " in function addHoverIcon");
System.out.println("button: " + image);
return;
}
final ImageIcon defaultIcon = new ImageIcon(defaultImg);
final ImageIcon icon = new ImageIcon(img);
button.setIcon(defaultIcon);
button.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){
button.setIcon(icon);
button.repaint();
}
public void mouseExited(MouseEvent e){
button.setIcon(defaultIcon);
button.repaint();
}
});
}
}
| true | true |
private JLabel blockForInputCharacter(JPanel panel, ImagePanel infoPanel, String difficultyValue, Map map, JPanel playerPanel, ArrayList<Player> players) {
try { Thread.sleep(100); } catch (Exception e) {}
JLabel charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
JLabel colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
JLabel colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
System.out.println("pLAYER SIZE " +players.size());
JTextField difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
JLabel map1 = addLabelToPanel(infoPanel, 21 , 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
JLabel photo = addLabelToPanel(playerPanel, 200 + (players.size()*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
panel.repaint();
playerPanel.repaint();
String oldState = states[1];
System.out.println(states[2]);
String oldState2 = states[3];
int currentPlayer = players.size();
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
if (!oldState.equals(states[1])){
panel.remove(colors);
colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
infoPanel.remove(map1);
map1 = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
infoPanel.remove(difficultyText);
difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
if(states[1].equals("human")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("elephant")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 275, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("squirrel")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 450, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("frog")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 619, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("cat")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 787, 210, 45, 24, "/media/uparrow.png");
}
infoPanel.repaint();
panel.repaint();
oldState = states[1];
}
if (!oldState2.equals(states[3])) {
playerPanel.remove(photo);
photo = addLabelToPanel(playerPanel, 200 + (currentPlayer*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
if(states[3].equals("red")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("blue")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 275, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("pink")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 450, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("green")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 619, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("orange")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 787, 482, 45, 24, "/media/uparrow.png");
}
panel.repaint();
playerPanel.repaint();
oldState2 = states[3];
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
return colors;
}
|
private JLabel blockForInputCharacter(JPanel panel, ImagePanel infoPanel, String difficultyValue, Map map, JPanel playerPanel, ArrayList<Player> players) {
try { Thread.sleep(100); } catch (Exception e) {}
JLabel charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
JLabel colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
JLabel colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
JTextField difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
JLabel map1 = addLabelToPanel(infoPanel, 21 , 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
JLabel photo = addLabelToPanel(playerPanel, 200 + (players.size()*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
panel.repaint();
playerPanel.repaint();
String oldState = states[1];
System.out.println(states[2]);
String oldState2 = states[3];
int currentPlayer = players.size();
boolean waitingSafe = true; // used to avoid race condition
while (waitingSafe) {
if (!oldState.equals(states[1])){
panel.remove(colors);
colors = addLabelToPanel(panel, 57, 247, 839, 226, "/media/" + states[1] + ".png");
infoPanel.remove(map1);
map1 = addLabelToPanel(infoPanel, 21, 37, 119, 66, "/media/m"+ map.getMapNum()+ ".png");
infoPanel.remove(difficultyText);
difficultyText = drawDifficulty(infoPanel, difficultyValue, 0, 125, 162, 25);
if(states[1].equals("human")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 117, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("elephant")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 275, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("squirrel")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 450, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("frog")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 619, 210, 45, 24, "/media/uparrow.png");
}
else if(states[1].equals("cat")){
panel.remove(charArrow);
charArrow = addLabelToPanel(panel, 787, 210, 45, 24, "/media/uparrow.png");
}
infoPanel.repaint();
panel.repaint();
oldState = states[1];
}
if (!oldState2.equals(states[3])) {
playerPanel.remove(photo);
photo = addLabelToPanel(playerPanel, 200 + (currentPlayer*160), 20, 100, 130, "/media/" + states[1].charAt(0) + states[3].charAt(0) + ".png");
if(states[3].equals("red")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 117, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("blue")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 275, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("pink")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 450, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("green")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 619, 482, 45, 24, "/media/uparrow.png");
}
else if(states[3].equals("orange")){
panel.remove(colorArrow);
colorArrow = addLabelToPanel(panel, 787, 482, 45, 24, "/media/uparrow.png");
}
panel.repaint();
playerPanel.repaint();
oldState2 = states[3];
}
try {
lock.lock();
waitingSafe = waiting;
}
finally {
lock.unlock();
}
}
return colors;
}
|
diff --git a/plugins/org.eclipse.emf.compare.diff/src/org/eclipse/emf/compare/diff/service/DiffEngineRegistry.java b/plugins/org.eclipse.emf.compare.diff/src/org/eclipse/emf/compare/diff/service/DiffEngineRegistry.java
index 4d656eaa7..86df7b611 100644
--- a/plugins/org.eclipse.emf.compare.diff/src/org/eclipse/emf/compare/diff/service/DiffEngineRegistry.java
+++ b/plugins/org.eclipse.emf.compare.diff/src/org/eclipse/emf/compare/diff/service/DiffEngineRegistry.java
@@ -1,186 +1,190 @@
/*******************************************************************************
* Copyright (c) 2009 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.compare.diff.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.compare.diff.EMFCompareDiffMessages;
import org.eclipse.emf.compare.diff.engine.GenericDiffEngine;
import org.eclipse.emf.compare.diff.engine.IDiffEngine;
/* (non-javadoc) we make use of the ordering of the engines, do not change Map and List implementations. */
/**
* This registry will be initialized with all the diff engines that could be parsed from the extension points
* if Eclipse is running according to {@link EMFPlugin#IS_ECLIPSE_RUNNING}, else it will contain only the two
* generic ones. Clients can add their own diff engines in the registry for standalone usage.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
public final class DiffEngineRegistry extends HashMap<String, List<Object>> {
/** Singleton instance of the registry. */
public static final DiffEngineRegistry INSTANCE = new DiffEngineRegistry();
/** Wild card for file extensions. */
private static final String ALL_EXTENSIONS = "*"; //$NON-NLS-1$
/** Name of the extension point to parse for engines. */
private static final String DIFF_ENGINES_EXTENSION_POINT = "org.eclipse.emf.compare.diff.engine"; //$NON-NLS-1$
/** Serial version UID is used when deserializing Objects. */
private static final long serialVersionUID = 2237008034183610765L;
/** Externalized here to avoid too many distinct usages. */
private static final String TAG_ENGINE = "diffengine"; //$NON-NLS-1$
/**
* As this is a singleton, hide the default constructor. Access the instance through the field
* {@link #INSTANCE}.
*/
private DiffEngineRegistry() {
if (EMFPlugin.IS_ECLIPSE_RUNNING) {
parseExtensionMetadata();
} else {
// Add both generic engines
putValue(ALL_EXTENSIONS, new GenericDiffEngine());
}
}
/**
* This will return the list of engines available for a given fileExtension. Engines must have been
* registered through an extension point for this to return anything else than an empty list. Note that
* engines registered against {@value #ALL_EXTENSIONS} will always be returned at the end of this list.
*
* @param fileExtension
* Extension of the file we seek the diff engines for.
* @return The list of available engines.
*/
public List<DiffEngineDescriptor> getDescriptors(String fileExtension) {
final List<Object> specific = get(fileExtension);
final List<Object> candidates = new ArrayList<Object>(get(ALL_EXTENSIONS));
if (specific != null) {
candidates.addAll(0, specific);
}
final List<DiffEngineDescriptor> engines = new ArrayList<DiffEngineDescriptor>(candidates.size());
for (final Object value : candidates) {
if (value instanceof DiffEngineDescriptor) {
engines.add((DiffEngineDescriptor)value);
}
}
return engines;
}
/**
* Returns the highest priority {@link IDiffEngine} registered against the given file extension. Specific
* engines will always come before generic ones regardless of their priority. If engines have been
* manually added to the list, the latest added will be returned.
*
* @param fileExtension
* The extension of the file we need an {@link IDiffEngine} for.
* @return The best {@link IDiffEngine} for the given file extension.
*/
public IDiffEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
- final int highestPriority = -1;
+ int highestPriority = -1;
IDiffEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
+ highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
+ break;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
+ highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
+ break;
}
}
}
return highest;
}
/**
* Adds the given value in the list of engines known for the given extension.
*
* @param key
* The file extension we wish to add an engine for.
* @param value
* Engine to be added.
*/
public void putValue(String key, Object value) {
if (value instanceof IDiffEngine || value instanceof DiffEngineDescriptor) {
List<Object> values = get(key);
if (values != null) {
values.add(value);
} else {
values = new ArrayList<Object>();
values.add(value);
super.put(key, values);
}
} else
throw new IllegalArgumentException(EMFCompareDiffMessages.getString(
"DiffEngineRegistry.IllegalEngine", value.getClass().getName())); //$NON-NLS-1$
}
/**
* This will parse the given {@link IConfigurationElement configuration element} and return a descriptor
* for it if it describes an engine.
*
* @param configElement
* Configuration element to parse.
* @return {@link DiffEngineDescriptor} wrapped around <code>configElement</code> if it describes an
* engine, <code>null</code> otherwise.
*/
private DiffEngineDescriptor parseEngine(IConfigurationElement configElement) {
if (!configElement.getName().equals(TAG_ENGINE))
return null;
final DiffEngineDescriptor desc = new DiffEngineDescriptor(configElement);
return desc;
}
/**
* This will parse the currently running platform for extensions and store all the diff engines that can
* be found.
*/
private void parseExtensionMetadata() {
final IExtension[] extensions = Platform.getExtensionRegistry().getExtensionPoint(
DIFF_ENGINES_EXTENSION_POINT).getExtensions();
for (int i = 0; i < extensions.length; i++) {
final IConfigurationElement[] configElements = extensions[i].getConfigurationElements();
for (int j = 0; j < configElements.length; j++) {
final DiffEngineDescriptor desc = parseEngine(configElements[j]);
final String[] fileExtensions = desc.getFileExtension().split(","); //$NON-NLS-1$
for (final String ext : fileExtensions) {
putValue(ext, desc);
}
}
}
}
}
| false | true |
public IDiffEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
final int highestPriority = -1;
IDiffEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
}
}
}
return highest;
}
|
public IDiffEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
int highestPriority = -1;
IDiffEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
break;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof DiffEngineDescriptor) {
final DiffEngineDescriptor desc = (DiffEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IDiffEngine) {
highest = (IDiffEngine)engine;
break;
}
}
}
return highest;
}
|
diff --git a/Clinelympics/src/com/csoft/clinelympics/GameServlet.java b/Clinelympics/src/com/csoft/clinelympics/GameServlet.java
index c69acd8..9fa59cf 100644
--- a/Clinelympics/src/com/csoft/clinelympics/GameServlet.java
+++ b/Clinelympics/src/com/csoft/clinelympics/GameServlet.java
@@ -1,41 +1,48 @@
package com.csoft.clinelympics;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
@SuppressWarnings("serial")
public class GameServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query(Game.entityKind, new Game().getGameKey());
Filter isGame = new FilterPredicate(Game.gameNameName, FilterOperator.EQUAL, req.getParameter(Game.gameNameName).trim());
query.setFilter(isGame);
List<Entity> games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
if (games.size() == 0) {
- query = new Query(Game.entityKind, new Game().getGameKey()).addSort(Game.gameIDName, Query.SortDirection.DESCENDING);
+ int newID = 1;
+ query = new Query(Game.entityKind, new Game().getGameKey()).addSort(Game.gameIDName, Query.SortDirection.DESCENDING);
games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
- int newID = ((Long) games.get(0).getProperty(Game.gameIDName)).intValue() + 1;
+ if (games.size() > 0) {
+ newID = ((Long) games.get(0).getProperty(Game.gameIDName)).intValue() + 1;
+ }
Game game = new Game(newID,
req.getParameter(Game.gameNameName).trim(),
Boolean.parseBoolean(req.getParameter(Game.scoreTypeName).trim()));
datastore.put(game.createEntity());
+ } else {
+ if (games.size() > 1) System.out.println("Multiple games with name " + req.getParameter(Game.gameNameName));
+ games.get(0).setProperty(Game.scoreTypeName, Boolean.parseBoolean(req.getParameter(Game.scoreTypeName).trim()));
+ datastore.put(games.get(0));
}
resp.sendRedirect("/games.jsp");
}
}
| false | true |
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query(Game.entityKind, new Game().getGameKey());
Filter isGame = new FilterPredicate(Game.gameNameName, FilterOperator.EQUAL, req.getParameter(Game.gameNameName).trim());
query.setFilter(isGame);
List<Entity> games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
if (games.size() == 0) {
query = new Query(Game.entityKind, new Game().getGameKey()).addSort(Game.gameIDName, Query.SortDirection.DESCENDING);
games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
int newID = ((Long) games.get(0).getProperty(Game.gameIDName)).intValue() + 1;
Game game = new Game(newID,
req.getParameter(Game.gameNameName).trim(),
Boolean.parseBoolean(req.getParameter(Game.scoreTypeName).trim()));
datastore.put(game.createEntity());
}
resp.sendRedirect("/games.jsp");
}
|
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query(Game.entityKind, new Game().getGameKey());
Filter isGame = new FilterPredicate(Game.gameNameName, FilterOperator.EQUAL, req.getParameter(Game.gameNameName).trim());
query.setFilter(isGame);
List<Entity> games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
if (games.size() == 0) {
int newID = 1;
query = new Query(Game.entityKind, new Game().getGameKey()).addSort(Game.gameIDName, Query.SortDirection.DESCENDING);
games = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
if (games.size() > 0) {
newID = ((Long) games.get(0).getProperty(Game.gameIDName)).intValue() + 1;
}
Game game = new Game(newID,
req.getParameter(Game.gameNameName).trim(),
Boolean.parseBoolean(req.getParameter(Game.scoreTypeName).trim()));
datastore.put(game.createEntity());
} else {
if (games.size() > 1) System.out.println("Multiple games with name " + req.getParameter(Game.gameNameName));
games.get(0).setProperty(Game.scoreTypeName, Boolean.parseBoolean(req.getParameter(Game.scoreTypeName).trim()));
datastore.put(games.get(0));
}
resp.sendRedirect("/games.jsp");
}
|
diff --git a/core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java b/core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java
index 1f04cf5a0..ab3b53115 100644
--- a/core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java
+++ b/core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java
@@ -1,88 +1,90 @@
package hudson.maven.reporters;
import hudson.FilePath;
import hudson.Util;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenModule;
import hudson.maven.MavenReporter;
import hudson.maven.MavenReporterDescriptor;
import hudson.maven.MojoInfo;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.JavadocArchiver.JavadocAction;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import java.io.File;
import java.io.IOException;
/**
* Records the javadoc and archives it.
*
* @author Kohsuke Kawaguchi
*/
public class MavenJavadocArchiver extends MavenReporter {
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException {
if(!mojo.pluginName.matches("org.apache.maven.plugins","maven-javadoc-plugin"))
return true;
if(!mojo.getGoal().equals("javadoc"))
return true;
File destDir;
try {
- destDir = mojo.getConfigurationValue("outputDirectory", File.class);
+ destDir = mojo.getConfigurationValue("reportOutputDirectory", File.class);
+ if(destDir==null)
+ destDir = mojo.getConfigurationValue("outputDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError("Unable to obtain the destDir from javadoc mojo"));
build.setResult(Result.FAILURE);
return true;
}
if(destDir.exists()) {
// javadoc:javadoc just skips itself when the current project is not a java project
FilePath target = build.getProjectRootDir().child("javadoc");
try {
listener.getLogger().println("Archiving javadoc");
new FilePath(destDir).copyRecursiveTo("**/*",target);
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.fatalError("Unable to copy Javadoc from "+destDir+" to "+target));
build.setResult(Result.FAILURE);
}
build.registerAsProjectAction(this);
}
return true;
}
public Action getProjectAction(MavenModule project) {
return new JavadocAction(project);
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public static final class DescriptorImpl extends MavenReporterDescriptor {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private DescriptorImpl() {
super(MavenJavadocArchiver.class);
}
public String getDisplayName() {
return "Publish javadoc";
}
public MavenJavadocArchiver newAutoInstance(MavenModule module) {
return new MavenJavadocArchiver();
}
}
private static final long serialVersionUID = 1L;
}
| true | true |
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException {
if(!mojo.pluginName.matches("org.apache.maven.plugins","maven-javadoc-plugin"))
return true;
if(!mojo.getGoal().equals("javadoc"))
return true;
File destDir;
try {
destDir = mojo.getConfigurationValue("outputDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError("Unable to obtain the destDir from javadoc mojo"));
build.setResult(Result.FAILURE);
return true;
}
if(destDir.exists()) {
// javadoc:javadoc just skips itself when the current project is not a java project
FilePath target = build.getProjectRootDir().child("javadoc");
try {
listener.getLogger().println("Archiving javadoc");
new FilePath(destDir).copyRecursiveTo("**/*",target);
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.fatalError("Unable to copy Javadoc from "+destDir+" to "+target));
build.setResult(Result.FAILURE);
}
build.registerAsProjectAction(this);
}
return true;
}
|
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException {
if(!mojo.pluginName.matches("org.apache.maven.plugins","maven-javadoc-plugin"))
return true;
if(!mojo.getGoal().equals("javadoc"))
return true;
File destDir;
try {
destDir = mojo.getConfigurationValue("reportOutputDirectory", File.class);
if(destDir==null)
destDir = mojo.getConfigurationValue("outputDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError("Unable to obtain the destDir from javadoc mojo"));
build.setResult(Result.FAILURE);
return true;
}
if(destDir.exists()) {
// javadoc:javadoc just skips itself when the current project is not a java project
FilePath target = build.getProjectRootDir().child("javadoc");
try {
listener.getLogger().println("Archiving javadoc");
new FilePath(destDir).copyRecursiveTo("**/*",target);
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.fatalError("Unable to copy Javadoc from "+destDir+" to "+target));
build.setResult(Result.FAILURE);
}
build.registerAsProjectAction(this);
}
return true;
}
|
diff --git a/connection-ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.java b/connection-ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.java
index 8a7e8b7a1..a251ecfb0 100644
--- a/connection-ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.java
+++ b/connection-ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.java
@@ -1,159 +1,159 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.connection.ui;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
/**
* The ConnectionParameterPageManager manages the {@link ConnectionParameterPage}s.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ConnectionParameterPageManager
{
/**
* Gets the connection parameter pages by searching for connection parameter page
* extensions.
*
* @return the connection parameter pages
*/
public static ConnectionParameterPage[] getConnectionParameterPages()
{
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry.getExtensionPoint( ConnectionUIPlugin.getDefault()
.getPluginProperties().getString( "ExtensionPoint_ConnectionParameterPages_id" ) ); //$NON-NLS-1$
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
final Map<String, ConnectionParameterPage> pageMap = new HashMap<String, ConnectionParameterPage>();
// For each extension: instantiate the page
for ( int m = 0; m < members.length; m++ )
{
IConfigurationElement member = members[m];
try
{
ConnectionParameterPage page = ( ConnectionParameterPage ) member.createExecutableExtension( "class" ); //$NON-NLS-1$
page.setPageId( member.getAttribute( "id" ) ); //$NON-NLS-1$
page.setPageName( member.getAttribute( "name" ) ); //$NON-NLS-1$
page.setPageDescription( member.getAttribute( "description" ) ); //$NON-NLS-1$
page.setPageDependsOnId( member.getAttribute( "dependsOnId" ) ); //$NON-NLS-1$
pageMap.put( page.getPageId(), page );
}
catch ( Exception e )
{
ConnectionUIPlugin.getDefault().getLog().log(
new Status( IStatus.ERROR, ConnectionUIConstants.PLUGIN_ID, 1,
Messages.getString("ConnectionParameterPageManager.UnableCreateConnectionParamPage") + member.getAttribute( "class" ), e ) ); //$NON-NLS-1$//$NON-NLS-2$
}
}
final ConnectionParameterPage[] pages = pageMap.values().toArray( new ConnectionParameterPage[0] );
Comparator<? super ConnectionParameterPage> pageComparator = new Comparator<ConnectionParameterPage>()
{
public int compare( ConnectionParameterPage p1, ConnectionParameterPage p2 )
{
String dependsOnId1 = p1.getPageDependsOnId();
String dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId1 );
- if ( page != null )
+ if ( page != null && !page.getPageDependsOnId().equals( dependsOnId1 ) )
{
dependsOnId1 = page.getPageDependsOnId();
}
else
{
dependsOnId1 = null;
}
}
while ( dependsOnId1 != null && !dependsOnId1.equals( p1.getPageId() ) );
dependsOnId1 = p1.getPageDependsOnId();
dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId2 );
if ( page != null )
{
dependsOnId2 = page.getPageDependsOnId();
}
else
{
dependsOnId2 = null;
}
}
while ( dependsOnId2 != null && !dependsOnId2.equals( p2.getPageId() ) );
return 0;
}
};
Arrays.sort( pages, pageComparator );
return pages;
}
}
| true | true |
public static ConnectionParameterPage[] getConnectionParameterPages()
{
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry.getExtensionPoint( ConnectionUIPlugin.getDefault()
.getPluginProperties().getString( "ExtensionPoint_ConnectionParameterPages_id" ) ); //$NON-NLS-1$
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
final Map<String, ConnectionParameterPage> pageMap = new HashMap<String, ConnectionParameterPage>();
// For each extension: instantiate the page
for ( int m = 0; m < members.length; m++ )
{
IConfigurationElement member = members[m];
try
{
ConnectionParameterPage page = ( ConnectionParameterPage ) member.createExecutableExtension( "class" ); //$NON-NLS-1$
page.setPageId( member.getAttribute( "id" ) ); //$NON-NLS-1$
page.setPageName( member.getAttribute( "name" ) ); //$NON-NLS-1$
page.setPageDescription( member.getAttribute( "description" ) ); //$NON-NLS-1$
page.setPageDependsOnId( member.getAttribute( "dependsOnId" ) ); //$NON-NLS-1$
pageMap.put( page.getPageId(), page );
}
catch ( Exception e )
{
ConnectionUIPlugin.getDefault().getLog().log(
new Status( IStatus.ERROR, ConnectionUIConstants.PLUGIN_ID, 1,
Messages.getString("ConnectionParameterPageManager.UnableCreateConnectionParamPage") + member.getAttribute( "class" ), e ) ); //$NON-NLS-1$//$NON-NLS-2$
}
}
final ConnectionParameterPage[] pages = pageMap.values().toArray( new ConnectionParameterPage[0] );
Comparator<? super ConnectionParameterPage> pageComparator = new Comparator<ConnectionParameterPage>()
{
public int compare( ConnectionParameterPage p1, ConnectionParameterPage p2 )
{
String dependsOnId1 = p1.getPageDependsOnId();
String dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId1 );
if ( page != null )
{
dependsOnId1 = page.getPageDependsOnId();
}
else
{
dependsOnId1 = null;
}
}
while ( dependsOnId1 != null && !dependsOnId1.equals( p1.getPageId() ) );
dependsOnId1 = p1.getPageDependsOnId();
dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId2 );
if ( page != null )
{
dependsOnId2 = page.getPageDependsOnId();
}
else
{
dependsOnId2 = null;
}
}
while ( dependsOnId2 != null && !dependsOnId2.equals( p2.getPageId() ) );
return 0;
}
};
Arrays.sort( pages, pageComparator );
return pages;
}
|
public static ConnectionParameterPage[] getConnectionParameterPages()
{
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry.getExtensionPoint( ConnectionUIPlugin.getDefault()
.getPluginProperties().getString( "ExtensionPoint_ConnectionParameterPages_id" ) ); //$NON-NLS-1$
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
final Map<String, ConnectionParameterPage> pageMap = new HashMap<String, ConnectionParameterPage>();
// For each extension: instantiate the page
for ( int m = 0; m < members.length; m++ )
{
IConfigurationElement member = members[m];
try
{
ConnectionParameterPage page = ( ConnectionParameterPage ) member.createExecutableExtension( "class" ); //$NON-NLS-1$
page.setPageId( member.getAttribute( "id" ) ); //$NON-NLS-1$
page.setPageName( member.getAttribute( "name" ) ); //$NON-NLS-1$
page.setPageDescription( member.getAttribute( "description" ) ); //$NON-NLS-1$
page.setPageDependsOnId( member.getAttribute( "dependsOnId" ) ); //$NON-NLS-1$
pageMap.put( page.getPageId(), page );
}
catch ( Exception e )
{
ConnectionUIPlugin.getDefault().getLog().log(
new Status( IStatus.ERROR, ConnectionUIConstants.PLUGIN_ID, 1,
Messages.getString("ConnectionParameterPageManager.UnableCreateConnectionParamPage") + member.getAttribute( "class" ), e ) ); //$NON-NLS-1$//$NON-NLS-2$
}
}
final ConnectionParameterPage[] pages = pageMap.values().toArray( new ConnectionParameterPage[0] );
Comparator<? super ConnectionParameterPage> pageComparator = new Comparator<ConnectionParameterPage>()
{
public int compare( ConnectionParameterPage p1, ConnectionParameterPage p2 )
{
String dependsOnId1 = p1.getPageDependsOnId();
String dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId1 );
if ( page != null && !page.getPageDependsOnId().equals( dependsOnId1 ) )
{
dependsOnId1 = page.getPageDependsOnId();
}
else
{
dependsOnId1 = null;
}
}
while ( dependsOnId1 != null && !dependsOnId1.equals( p1.getPageId() ) );
dependsOnId1 = p1.getPageDependsOnId();
dependsOnId2 = p2.getPageDependsOnId();
do
{
if ( dependsOnId1 == null && dependsOnId2 != null )
{
return -1;
}
else if ( dependsOnId2 == null && dependsOnId1 != null )
{
return 1;
}
else if ( dependsOnId1 != null && dependsOnId1.equals( p2.getPageId() ) )
{
return 1;
}
else if ( dependsOnId2 != null && dependsOnId2.equals( p1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId2 );
if ( page != null )
{
dependsOnId2 = page.getPageDependsOnId();
}
else
{
dependsOnId2 = null;
}
}
while ( dependsOnId2 != null && !dependsOnId2.equals( p2.getPageId() ) );
return 0;
}
};
Arrays.sort( pages, pageComparator );
return pages;
}
|
diff --git a/NoItem/src/net/worldoftomorrow/nala/ni/Vault.java b/NoItem/src/net/worldoftomorrow/nala/ni/Vault.java
index 8dec02c..3a0d912 100644
--- a/NoItem/src/net/worldoftomorrow/nala/ni/Vault.java
+++ b/NoItem/src/net/worldoftomorrow/nala/ni/Vault.java
@@ -1,40 +1,40 @@
package net.worldoftomorrow.nala.ni;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import net.milkbowl.vault.permission.Permission;
public class Vault {
private NoItem plugin;
protected static boolean vaultPerms = false;
public Vault(NoItem plugin) {
this.plugin = plugin;
vaultPerms = this.setupPerms();
}
private static Permission permission = null;
private boolean setupPerms() {
try {
RegisteredServiceProvider<Permission> permProvider = plugin
.getServer()
.getServicesManager()
.getRegistration(
net.milkbowl.vault.permission.Permission.class);
if (permProvider != null) {
permission = permProvider.getProvider();
- Log.info("[NoItem] Hooked into vault for permissions.");
+ Log.info("Hooked into vault for permissions.");
}
} catch (NoClassDefFoundError e) {
- Log.info("[NoItem] Vault not found, using superPerms.");
+ Log.info("Vault not found, using superPerms.");
}
return permission != null;
}
protected static boolean has(Player p, String perm) {
return permission.has(p, perm);
}
}
| false | true |
private boolean setupPerms() {
try {
RegisteredServiceProvider<Permission> permProvider = plugin
.getServer()
.getServicesManager()
.getRegistration(
net.milkbowl.vault.permission.Permission.class);
if (permProvider != null) {
permission = permProvider.getProvider();
Log.info("[NoItem] Hooked into vault for permissions.");
}
} catch (NoClassDefFoundError e) {
Log.info("[NoItem] Vault not found, using superPerms.");
}
return permission != null;
}
|
private boolean setupPerms() {
try {
RegisteredServiceProvider<Permission> permProvider = plugin
.getServer()
.getServicesManager()
.getRegistration(
net.milkbowl.vault.permission.Permission.class);
if (permProvider != null) {
permission = permProvider.getProvider();
Log.info("Hooked into vault for permissions.");
}
} catch (NoClassDefFoundError e) {
Log.info("Vault not found, using superPerms.");
}
return permission != null;
}
|
diff --git a/geotools2/geotools-src/filter/src/org/geotools/filter/SQLUnpacker.java b/geotools2/geotools-src/filter/src/org/geotools/filter/SQLUnpacker.java
index bc31837dd..12318876f 100644
--- a/geotools2/geotools-src/filter/src/org/geotools/filter/SQLUnpacker.java
+++ b/geotools2/geotools-src/filter/src/org/geotools/filter/SQLUnpacker.java
@@ -1,285 +1,286 @@
/*
* Geotools - OpenSource mapping toolkit
* (C) 2002, Centre for Computational Geography
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.geotools.filter;
import java.util.*;
/**
* Determines which parts of a Filter can be turned into valid SQL statements.
* Given a filter it constructs two filters, one of the supported parts of
* the filter passed in, one of the unsupported. If one of the constructed
* filters is null (ie the whole filter is supported or unsupported), it is the
* clients responsibility to deal with that. The SQLUnpacker should be tightly
* coordinated with the SQLEncoder. The SQLEncoder passes its Capabilities (ie
* which filters it can encode and which it can't) to the Unpacker, and the
* Unpacker returns a supported filter, which should be passed to the Encoder as
* the Encoder Capabilities claimed to fully support everything in the supported
* filter. The unsupported filter should be used after the SQL statement is
* executed, testing each feature in the result set with the contains method.
*
* <p>
* This Unpacker can likely be easily used with any Encoder that has a FilterCapabilities
* of the actions it can perform. May want to rename it FilterUnpacker, as it is
* likely generic enough, but for now this name should be fine, to emphasize that
* the SQLEncoder needs to be closely linked to it to work properly.
*
* @author Chris Holmes, TOPP
*/
public class SQLUnpacker {
/** FilterPair is an inner class, for holding the unsupported
and supported filters */
private FilterPair pair;
/** The types of Filters that should be part of the supported Filter */
private FilterCapabilities capabilities;
/**
* Constructor with FilterCapabilities from the Encoder used
* in conjunction with this Unpacker.
*
* @param capabilities what FilterTypes should be supported.
*/
public SQLUnpacker(FilterCapabilities capabilities) {
this.capabilities = capabilities;
}
/**
* Performs the unpacking of the filter, to get the results of
* the unpacking, getUnSupported() and getSupported() must be called.
*
* @param filter to be unpacked.
* @deprecated unPacking now can be done splitting on an AND or an OR. unPackAND
* replaces this generic unPack (which assumed an AND unpacking), and
* unPackOR is added to handle the OR case. So use unPackAND where ever
* this is currently used.
*/
public void unPack(Filter filter){
//this can be easily changed to return a pair, but adding a FilterPair
//class to the Filter package seems to add unnecessary clutter.
pair = doUnPack(filter, AbstractFilter.LOGIC_AND);
}
/**
* Performs the unpacking of a filter, for the cases when ANDs can
* be spit and ORs can not. To get the results of the unpacking
* getUnsupported and getSupported must be called before another unpacking
* is done.
*
*@param filter to be unpacked, split on ANDs
*/
public void unPackAND(Filter filter){
pair = doUnPack(filter, AbstractFilter.LOGIC_AND);
}
/**
* Performs the unpacking of a filter, for the cases when ORs can
* be split and ANDs can not. To get the results of the unpacking
* getUnsupported and getSupported must be called before another unpacking
* is done.
*
*@param filter to be unpacked, split on ANDs
*/
public void unPackOR(Filter filter){
pair = doUnPack(filter, AbstractFilter.LOGIC_OR);
}
/**
* After an unPack has been called, returns the resulting
* Filter of the unsupported parts of the unPacked filter.
* If the unPacked filter is fully supported this returns
* a null, it is the client's responsibility to deal with it.
* If there are multiple unsupported subfilters they are ANDed
* together.
*
* @return A filter of the unsupported parts of the unPacked filter.
*/
public Filter getUnSupported(){
return pair.getUnSupported();
}
/**
* After an unPack has been called, returns the resulting
* Filter of the supported parts of the unPacked filter.
* If the unPacked filter is not supported at all this returns
* a null, it is the client's responsibility to deal with it.
* If there are multiple supported subfilters they are ANDed
* together.
*
* @return A filter of the supported parts of the unPacked filter.
*/
public Filter getSupported(){
return pair.getSupported();
}
/**
* Performs the actual recursive unpacking of the filter. Can do the unpacking
* on either AND or OR filters.
* @param filter the filter to be split
* @param splitType the short representation of the logic filter to recursively unpack.
* @return A filter of the unsupported parts of the unPacked filter.
*/
private FilterPair doUnPack(Filter filter, short splitType) {
/* Implementation notes:
* This is recursive, so it's worth explaining. The base cases are either
* the filter is fully supported, ie all of its subFilters are supported, and
* thus it can be totally encoded, or it is not supported. The recursive cases
* are when the filter is not fully supported and it is an AND or a NOT filter.
* In these cases the filter can be split up, and each subfilter can return some
* supported filters and some unsupported filters. If it is an OR filter and not
* fully supported we can descend no further, as each part of the OR needs to be
* tested, we can't put part in the SQL statement and part in the filter. So if
* it is an AND filter, we get teh subFilters and call doUnPack on each subFilter,
* combining the Unsupported and Supported FilterPairs of each subFilter into a single
* filter pair, which is the pair we will return. If a subfilter in turn is an AND with
* its own subfilters, they return their own unSupported and Supported filters, because
* it will eventually hit the base case. The base cases return null for half of the
* filter pair, and return the filter for the other half, depending on if it's unsupported
* or supported. For the NOT filter, it just descends further, unpacking the filter
* inside the NOT, and then tacking NOTs on the supported and unsupported sub filters.
*---addition: No longer just ANDs supported. ORs can be split, same as previous
* paragraph, but switch ORs with ANDs, there are cases, such as the delete statement,
* where we have to split on ORs and can't on ANDs (opposite of get statement). Should
* work the same, just a different logic filter.
*/
FilterPair retPair;
FilterPair subPair;
Filter subSup = null; //for logic iteration
Filter subUnSup = null; //for logic iteration
Filter retSup = null; //for return pair
Filter retUnSup = null; //for return pair
+ if (filter == null) return new FilterPair(null, null);
if (capabilities.fullySupports(filter)) {
retSup = filter;
} else {
short type = ((AbstractFilter)filter).getFilterType();
if (type == splitType && capabilities.supports(splitType)){
//TODO: one special case not covered, when capabilities does not support
// AND and it perfectly splits the filter into unsupported and supported
Iterator filters = ((LogicFilter)filter).getFilterIterator();
while (filters.hasNext()) {
subPair = doUnPack((Filter)filters.next(), splitType);
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
retSup = combineFilters(retSup, subSup, splitType);
retUnSup = combineFilters(retUnSup, subUnSup, splitType);
}
} else if ( type == AbstractFilter.LOGIC_NOT &&
capabilities.supports(AbstractFilter.LOGIC_NOT)){
Iterator filters = ((LogicFilter)filter).getFilterIterator();
subPair = doUnPack((Filter)filters.next(), splitType); //NOT only has one
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
if (subSup != null){
retSup = subUnSup.not();
}
if (subUnSup != null){
retUnSup = subUnSup.not();
}
} else { //it's not supported and has no logic subfilters to be split.
retUnSup = filter;
}
}
retPair = new FilterPair(retSup, retUnSup);
return retPair;
}
/**
* Combines two filters, which may be null, into one. If one
* is null and the other not, it returns the one that's not. If
* both are null returns null.
*
* @param filter1 one filter to be combined.
* @param filter2 the other filter to be combined.
* @return the resulting combined filter.
*/
private Filter combineFilters(Filter filter1, Filter filter2, short splitType){
Filter retFilter;
if (filter1 != null) {
if (filter2 != null){
if (splitType == AbstractFilter.LOGIC_AND) {
retFilter = filter1.and(filter2);
} else { //OR and AND only split types, this must be or.
retFilter = filter1.or(filter2);
}
} else {
retFilter = filter1;
}
} else {
if (filter2 != null) {
retFilter = filter2;
} else {
retFilter = null;
}
}
return retFilter;
}
/**
* An inner class to hold a pair of Filters.
* Reasoning behind inner class is that if made public it would
* clutter up the filter folder with a FilterPair, which seems
* like it might be widely used, but is only necessary for one
* class. To return filter pairs would be slightly cleaner, in terms
* of writing code, but this way is cleaner for the geotools filter module.
*/
private class FilterPair {
/** half of the filter pair */
private Filter supported;
/** the other half */
private Filter unSupported;
/**
* Constructor takes the two filters of the pair.
*
* @param supported The filter that can be encoded.
* @param unSupported the filter that can't be encoded.
*/
public FilterPair(Filter supported, Filter unSupported){
this.supported = supported;
this.unSupported = unSupported;
}
/**
* Accessor method.
*
*@return the supported Filter.
*/
public Filter getSupported(){
return supported;
}
/**
* Accessor method.
*
*@return the unSupported Filter.
*/
public Filter getUnSupported(){
return unSupported;
}
}
}
| true | true |
private FilterPair doUnPack(Filter filter, short splitType) {
/* Implementation notes:
* This is recursive, so it's worth explaining. The base cases are either
* the filter is fully supported, ie all of its subFilters are supported, and
* thus it can be totally encoded, or it is not supported. The recursive cases
* are when the filter is not fully supported and it is an AND or a NOT filter.
* In these cases the filter can be split up, and each subfilter can return some
* supported filters and some unsupported filters. If it is an OR filter and not
* fully supported we can descend no further, as each part of the OR needs to be
* tested, we can't put part in the SQL statement and part in the filter. So if
* it is an AND filter, we get teh subFilters and call doUnPack on each subFilter,
* combining the Unsupported and Supported FilterPairs of each subFilter into a single
* filter pair, which is the pair we will return. If a subfilter in turn is an AND with
* its own subfilters, they return their own unSupported and Supported filters, because
* it will eventually hit the base case. The base cases return null for half of the
* filter pair, and return the filter for the other half, depending on if it's unsupported
* or supported. For the NOT filter, it just descends further, unpacking the filter
* inside the NOT, and then tacking NOTs on the supported and unsupported sub filters.
*---addition: No longer just ANDs supported. ORs can be split, same as previous
* paragraph, but switch ORs with ANDs, there are cases, such as the delete statement,
* where we have to split on ORs and can't on ANDs (opposite of get statement). Should
* work the same, just a different logic filter.
*/
FilterPair retPair;
FilterPair subPair;
Filter subSup = null; //for logic iteration
Filter subUnSup = null; //for logic iteration
Filter retSup = null; //for return pair
Filter retUnSup = null; //for return pair
if (capabilities.fullySupports(filter)) {
retSup = filter;
} else {
short type = ((AbstractFilter)filter).getFilterType();
if (type == splitType && capabilities.supports(splitType)){
//TODO: one special case not covered, when capabilities does not support
// AND and it perfectly splits the filter into unsupported and supported
Iterator filters = ((LogicFilter)filter).getFilterIterator();
while (filters.hasNext()) {
subPair = doUnPack((Filter)filters.next(), splitType);
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
retSup = combineFilters(retSup, subSup, splitType);
retUnSup = combineFilters(retUnSup, subUnSup, splitType);
}
} else if ( type == AbstractFilter.LOGIC_NOT &&
capabilities.supports(AbstractFilter.LOGIC_NOT)){
Iterator filters = ((LogicFilter)filter).getFilterIterator();
subPair = doUnPack((Filter)filters.next(), splitType); //NOT only has one
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
if (subSup != null){
retSup = subUnSup.not();
}
if (subUnSup != null){
retUnSup = subUnSup.not();
}
} else { //it's not supported and has no logic subfilters to be split.
retUnSup = filter;
}
}
retPair = new FilterPair(retSup, retUnSup);
return retPair;
}
|
private FilterPair doUnPack(Filter filter, short splitType) {
/* Implementation notes:
* This is recursive, so it's worth explaining. The base cases are either
* the filter is fully supported, ie all of its subFilters are supported, and
* thus it can be totally encoded, or it is not supported. The recursive cases
* are when the filter is not fully supported and it is an AND or a NOT filter.
* In these cases the filter can be split up, and each subfilter can return some
* supported filters and some unsupported filters. If it is an OR filter and not
* fully supported we can descend no further, as each part of the OR needs to be
* tested, we can't put part in the SQL statement and part in the filter. So if
* it is an AND filter, we get teh subFilters and call doUnPack on each subFilter,
* combining the Unsupported and Supported FilterPairs of each subFilter into a single
* filter pair, which is the pair we will return. If a subfilter in turn is an AND with
* its own subfilters, they return their own unSupported and Supported filters, because
* it will eventually hit the base case. The base cases return null for half of the
* filter pair, and return the filter for the other half, depending on if it's unsupported
* or supported. For the NOT filter, it just descends further, unpacking the filter
* inside the NOT, and then tacking NOTs on the supported and unsupported sub filters.
*---addition: No longer just ANDs supported. ORs can be split, same as previous
* paragraph, but switch ORs with ANDs, there are cases, such as the delete statement,
* where we have to split on ORs and can't on ANDs (opposite of get statement). Should
* work the same, just a different logic filter.
*/
FilterPair retPair;
FilterPair subPair;
Filter subSup = null; //for logic iteration
Filter subUnSup = null; //for logic iteration
Filter retSup = null; //for return pair
Filter retUnSup = null; //for return pair
if (filter == null) return new FilterPair(null, null);
if (capabilities.fullySupports(filter)) {
retSup = filter;
} else {
short type = ((AbstractFilter)filter).getFilterType();
if (type == splitType && capabilities.supports(splitType)){
//TODO: one special case not covered, when capabilities does not support
// AND and it perfectly splits the filter into unsupported and supported
Iterator filters = ((LogicFilter)filter).getFilterIterator();
while (filters.hasNext()) {
subPair = doUnPack((Filter)filters.next(), splitType);
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
retSup = combineFilters(retSup, subSup, splitType);
retUnSup = combineFilters(retUnSup, subUnSup, splitType);
}
} else if ( type == AbstractFilter.LOGIC_NOT &&
capabilities.supports(AbstractFilter.LOGIC_NOT)){
Iterator filters = ((LogicFilter)filter).getFilterIterator();
subPair = doUnPack((Filter)filters.next(), splitType); //NOT only has one
subSup = subPair.getSupported();
subUnSup = subPair.getUnSupported();
if (subSup != null){
retSup = subUnSup.not();
}
if (subUnSup != null){
retUnSup = subUnSup.not();
}
} else { //it's not supported and has no logic subfilters to be split.
retUnSup = filter;
}
}
retPair = new FilterPair(retSup, retUnSup);
return retPair;
}
|
diff --git a/common/net.sf.okapi.common/src/net/sf/okapi/common/ParametersString.java b/common/net.sf.okapi.common/src/net/sf/okapi/common/ParametersString.java
index 549d32522..1ad797c11 100644
--- a/common/net.sf.okapi.common/src/net/sf/okapi/common/ParametersString.java
+++ b/common/net.sf.okapi.common/src/net/sf/okapi/common/ParametersString.java
@@ -1,255 +1,255 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.common;
/**
* String-based representation of a set of parameters.
*/
import java.util.Iterator;
import java.util.LinkedHashMap;
public class ParametersString {
private LinkedHashMap<String, Object> list;
public ParametersString () {
list = new LinkedHashMap<String, Object>();
}
public ParametersString (String data) {
list = new LinkedHashMap<String, Object>();
buildList(null, data);
}
@Override
public String toString () {
return buildString(null);
}
public void fromString (String data) {
list.clear();
buildList(null, data);
}
public void reset () {
list.clear();
}
public void remove (String name) {
if ( list.containsKey(name) ) {
list.remove(name);
}
}
public void removeGroup (String groupName) {
groupName += ".";
Iterator<String> iter = list.keySet().iterator();
String key;
while ( iter.hasNext() ) {
key = iter.next();
if ( key.startsWith(groupName) ) {
list.remove(key);
}
}
}
private String escape (String value) {
if ( value == null ) return value;
value = value.replace("\r", "$0d$");
return value.replace("\n", "$0a$");
}
private String unescape (String value) {
if ( value == null ) return value;
value = value.replace("$0d$", "\r");
return value.replace("$0a$", "\n");
}
private String buildString (String prefix) {
StringBuilder tmp = new StringBuilder("#v1");
Object value;
if ( prefix != null ) prefix += ".";
for ( String key : list.keySet() ) {
// Check the group prefix if required
if ( prefix != null ) {
if ( !key.startsWith(prefix) ) continue;
tmp.append("\n"+key.substring(prefix.length()));
}
else tmp.append("\n"+key);
// Add to the string
value = list.get(key);
if ( value instanceof String ) {
tmp.append("="+escape((String)value));
}
else if ( value instanceof Integer ) {
tmp.append(".i="+String.valueOf(value));
}
else if ( value instanceof Boolean ) {
tmp.append(".b="+((Boolean)value ? "true" : "false"));
}
else {
throw new RuntimeException("Invalide type: "+key);
}
}
return tmp.toString();
}
private void buildList (String prefix,
String data)
{
if ( prefix == null ) prefix = "";
else prefix += ".";
String[] lines = data.split("\n", 0);
int n;
String qualifiedName;
String key;
String value;
for ( String line : lines ) {
if ( line.length() == 0 ) continue;
if ( line.charAt(0) == '#' ) continue;
if (( n = line.indexOf('=')) == -1 ) continue;
- qualifiedName = line.trim().substring(0, n).trim();
- value = line.trim().substring(n+1).trim();
+ qualifiedName = line.substring(0, n).trim();
+ value = line.substring(n+1).trim();
if ( qualifiedName.endsWith(".b") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, "true".equals(value));
}
else if ( qualifiedName.endsWith(".i") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, (int)Integer.valueOf(value));
}
else {
key = prefix + qualifiedName;
list.put(key, unescape(value));
}
}
}
public String getGroup (String name,
String defaultValue)
{
String tmp = buildString(name);
if ( tmp.length() > 0 ) return tmp;
// Else: return default value
return defaultValue;
}
public String getGroup (String name) {
return buildString(name);
}
public void setGroup (String name,
String data)
{
buildList(name, data);
}
public void setGroup (String name,
ParametersString params)
{
if ( name == null ) name = "";
else name += ".";
for ( String key : params.list.keySet() ) {
list.put(name+key, params.list.get(key));
}
}
public String getString (String name,
String defaultValue)
{
if ( list.containsKey(name) )
return (String)list.get(name);
// Else: return default value.
return defaultValue;
}
public String getString (String name) {
return getString(name, "");
}
public void setString (String name,
String value)
{
if ( value == null ) list.remove(name);
else list.put(name, value);
}
public boolean getBoolean (String name,
boolean defaultValue)
{
if ( list.containsKey(name) )
return (Boolean)list.get(name);
// Else: return false by default.
return defaultValue;
}
public boolean getBoolean (String name) {
return getBoolean(name, false);
}
public void setBoolean (String name,
boolean value)
{
list.put(name, value);
}
public int getInteger (String name,
int defaultValue)
{
if ( list.containsKey(name) )
return (Integer)list.get(name);
// Else: return zero by default.
return defaultValue;
}
public int getInteger (String name) {
return getInteger(name, 0);
}
public void setInteger (String name,
int value)
{
list.put(name, value);
}
public void setParameter (String name,
String value)
{
setString(name, value);
}
public void setParameter (String name,
boolean value)
{
setBoolean(name, value);
}
public void setParameter (String name,
int value)
{
setInteger(name, value);
}
}
| true | true |
private void buildList (String prefix,
String data)
{
if ( prefix == null ) prefix = "";
else prefix += ".";
String[] lines = data.split("\n", 0);
int n;
String qualifiedName;
String key;
String value;
for ( String line : lines ) {
if ( line.length() == 0 ) continue;
if ( line.charAt(0) == '#' ) continue;
if (( n = line.indexOf('=')) == -1 ) continue;
qualifiedName = line.trim().substring(0, n).trim();
value = line.trim().substring(n+1).trim();
if ( qualifiedName.endsWith(".b") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, "true".equals(value));
}
else if ( qualifiedName.endsWith(".i") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, (int)Integer.valueOf(value));
}
else {
key = prefix + qualifiedName;
list.put(key, unescape(value));
}
}
}
|
private void buildList (String prefix,
String data)
{
if ( prefix == null ) prefix = "";
else prefix += ".";
String[] lines = data.split("\n", 0);
int n;
String qualifiedName;
String key;
String value;
for ( String line : lines ) {
if ( line.length() == 0 ) continue;
if ( line.charAt(0) == '#' ) continue;
if (( n = line.indexOf('=')) == -1 ) continue;
qualifiedName = line.substring(0, n).trim();
value = line.substring(n+1).trim();
if ( qualifiedName.endsWith(".b") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, "true".equals(value));
}
else if ( qualifiedName.endsWith(".i") ) {
key = prefix + qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
list.put(key, (int)Integer.valueOf(value));
}
else {
key = prefix + qualifiedName;
list.put(key, unescape(value));
}
}
}
|
diff --git a/src/r/builtins/Log.java b/src/r/builtins/Log.java
index 8d354de..499053a 100644
--- a/src/r/builtins/Log.java
+++ b/src/r/builtins/Log.java
@@ -1,34 +1,34 @@
package r.builtins;
import r.*;
import r.data.*;
import r.nodes.*;
import r.nodes.truffle.*;
/**
* "log"
*
* <pre>
* x -- a numeric or complex vector.
* base -- a positive or complex number: the base with respect to which logarithms are computed. Defaults to e=exp(1).
* </pre>
*/
// TODO: complex numbers
final class Log extends CallFactory {
static final CallFactory _ = new Log("log", new String[]{"x", "base"}, new String[]{"x"});
private Log(String name, String[] params, String[] required) {
super(name, params, required);
}
@Override public RNode create(ASTNode call, RSymbol[] names, RNode[] exprs) {
ArgumentInfo ia = check(call, names, exprs);
if (exprs.length == 1) { return Ln._.create(call, names, exprs); }
RNode baseExpr = exprs[ia.position("base")];
- if (Builtin.isNumericConstant(baseExpr, 10)) { return Log10._.create(call, names, exprs); }
- if (Builtin.isNumericConstant(baseExpr, 2)) { return Log2._.create(call, names, exprs); }
+ if (Builtin.isNumericConstant(baseExpr, 10)) { return Log10._.create(call, new RSymbol[]{names[ia.position("x")]}, new RNode[]{exprs[ia.position("base")]}); }
+ if (Builtin.isNumericConstant(baseExpr, 2)) { return Log2._.create(call, new RSymbol[]{names[ia.position("x")]}, new RNode[]{exprs[ia.position("base")]}); }
// TODO: implement the generic case
throw Utils.nyi("unsupported case");
}
}
| true | true |
@Override public RNode create(ASTNode call, RSymbol[] names, RNode[] exprs) {
ArgumentInfo ia = check(call, names, exprs);
if (exprs.length == 1) { return Ln._.create(call, names, exprs); }
RNode baseExpr = exprs[ia.position("base")];
if (Builtin.isNumericConstant(baseExpr, 10)) { return Log10._.create(call, names, exprs); }
if (Builtin.isNumericConstant(baseExpr, 2)) { return Log2._.create(call, names, exprs); }
// TODO: implement the generic case
throw Utils.nyi("unsupported case");
}
|
@Override public RNode create(ASTNode call, RSymbol[] names, RNode[] exprs) {
ArgumentInfo ia = check(call, names, exprs);
if (exprs.length == 1) { return Ln._.create(call, names, exprs); }
RNode baseExpr = exprs[ia.position("base")];
if (Builtin.isNumericConstant(baseExpr, 10)) { return Log10._.create(call, new RSymbol[]{names[ia.position("x")]}, new RNode[]{exprs[ia.position("base")]}); }
if (Builtin.isNumericConstant(baseExpr, 2)) { return Log2._.create(call, new RSymbol[]{names[ia.position("x")]}, new RNode[]{exprs[ia.position("base")]}); }
// TODO: implement the generic case
throw Utils.nyi("unsupported case");
}
|
diff --git a/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java b/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java
index b432b344..e360f457 100644
--- a/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java
+++ b/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java
@@ -1,229 +1,229 @@
/**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.grapher.graphviz;
import com.google.common.base.Join;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.grapher.ImplementationNode;
import com.google.inject.grapher.NodeAliasFactory;
import com.google.inject.grapher.Renderer;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* {@link Renderer} implementation that writes out a Graphviz DOT file of the
* graph. Bound in {@link GraphvizModule}.
* <p>
* Specify the {@link PrintWriter} to output to with
* {@link #setOut(PrintWriter)}.
*
* @author [email protected] (Pete Hopkins)
*/
public class GraphvizRenderer implements Renderer, NodeAliasFactory<String> {
private final List<GraphvizNode> nodes = Lists.newArrayList();
private final List<GraphvizEdge> edges = Lists.newArrayList();
private final Map<String, String> aliases = Maps.newHashMap();
private PrintWriter out;
private String rankdir = "TB";
public GraphvizRenderer setOut(PrintWriter out) {
this.out = out;
return this;
}
public GraphvizRenderer setRankdir(String rankdir) {
this.rankdir = rankdir;
return this;
}
public void addNode(GraphvizNode node) {
nodes.add(node);
}
public void addEdge(GraphvizEdge edge) {
edges.add(edge);
}
public void newAlias(String fromId, String toId) {
aliases.put(fromId, toId);
}
protected String resolveAlias(String id) {
while (aliases.containsKey(id)) {
id = aliases.get(id);
}
return id;
}
public void render() {
start();
for (GraphvizNode node : nodes) {
renderNode(node);
}
for (GraphvizEdge edge : edges) {
renderEdge(edge);
}
finish();
out.flush();
}
protected Map<String, String> getGraphAttributes() {
Map<String, String> attrs = Maps.newHashMap();
attrs.put("rankdir", rankdir);
return attrs;
}
protected void start() {
out.println("digraph injector {");
Map<String, String> attrs = getGraphAttributes();
out.println("graph " + getAttrString(attrs) + ";");
}
protected void finish() {
out.println("}");
}
protected void renderNode(GraphvizNode node) {
Map<String, String> attrs = getNodeAttributes(node);
out.println(node.getNodeId() + " " + getAttrString(attrs));
}
protected Map<String, String> getNodeAttributes(GraphvizNode node) {
Map<String, String> attrs = Maps.newHashMap();
attrs.put("label", getNodeLabel(node));
// remove most of the margin because the table has internal padding
attrs.put("margin", "0.02,0");
attrs.put("shape", node.getShape().toString());
attrs.put("style", node.getStyle().toString());
return attrs;
}
/**
* Creates the "label" for a node. This is a string of HTML that defines a
* table with a heading at the top and (in the case of
* {@link ImplementationNode}s) rows for each of the member fields.
*/
protected String getNodeLabel(GraphvizNode node) {
String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0";
StringBuilder html = new StringBuilder();
html.append("<");
html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\"");
html.append(cellborder).append("\" border=\"0\">");
html.append("<tr>").append("<td align=\"left\" port=\"header\" ");
html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">");
String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles());
if (subtitle.length() != 0) {
- html.append("<font align=\"left\" color=\"").append(node.getHeaderTextColor());
+ html.append("<font color=\"").append(node.getHeaderTextColor());
html.append("\" point-size=\"10\">");
html.append(subtitle).append("<br align=\"left\"/>").append("</font>");
}
html.append("<font color=\"" + node.getHeaderTextColor() + "\">");
html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>");
html.append("</font>").append("</td>").append("</tr>");
for (Map.Entry<String, String> field : node.getFields().entrySet()) {
html.append("<tr>");
html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">");
html.append(htmlEscape(field.getValue()));
html.append("</td>").append("</tr>");
}
html.append("</table>");
html.append(">");
return html.toString();
}
protected void renderEdge(GraphvizEdge edge) {
Map<String, String> attrs = getEdgeAttributes(edge);
String tailId = getEdgeEndPoint(resolveAlias(edge.getTailNodeId()), edge.getTailPortId(),
edge.getTailCompassPoint());
String headId = getEdgeEndPoint(resolveAlias(edge.getHeadNodeId()), edge.getHeadPortId(),
edge.getHeadCompassPoint());
out.println(tailId + " -> " + headId + " " + getAttrString(attrs));
}
protected Map<String, String> getEdgeAttributes(GraphvizEdge edge) {
Map<String, String> attrs = Maps.newHashMap();
attrs.put("arrowhead", getArrowString(edge.getArrowHead()));
attrs.put("arrowtail", getArrowString(edge.getArrowTail()));
attrs.put("style", edge.getStyle().toString());
return attrs;
}
private String getAttrString(Map<String, String> attrs) {
List<String> attrList = Lists.newArrayList();
for (Entry<String, String> attr : attrs.entrySet()) {
String value = attr.getValue();
if (value != null) {
attrList.add(attr.getKey() + "=" + value);
}
}
return "[" + Join.join(", ", attrList) + "]";
}
/**
* Turns a {@link List} of {@link ArrowType}s into a {@link String} that
* represents combining them. With Graphviz, that just means concatenating
* them.
*/
protected String getArrowString(List<ArrowType> arrows) {
return Join.join("", arrows);
}
protected String getEdgeEndPoint(String nodeId, String portId, CompassPoint compassPoint) {
List<String> portStrings = Lists.newArrayList(nodeId);
if (portId != null) {
portStrings.add(portId);
}
if (compassPoint != null) {
portStrings.add(compassPoint.toString());
}
return Join.join(":", portStrings);
}
protected String htmlEscape(String str) {
return str.replace("&", "&").replace("<", "<").replace(">", ">");
}
}
| true | true |
protected String getNodeLabel(GraphvizNode node) {
String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0";
StringBuilder html = new StringBuilder();
html.append("<");
html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\"");
html.append(cellborder).append("\" border=\"0\">");
html.append("<tr>").append("<td align=\"left\" port=\"header\" ");
html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">");
String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles());
if (subtitle.length() != 0) {
html.append("<font align=\"left\" color=\"").append(node.getHeaderTextColor());
html.append("\" point-size=\"10\">");
html.append(subtitle).append("<br align=\"left\"/>").append("</font>");
}
html.append("<font color=\"" + node.getHeaderTextColor() + "\">");
html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>");
html.append("</font>").append("</td>").append("</tr>");
for (Map.Entry<String, String> field : node.getFields().entrySet()) {
html.append("<tr>");
html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">");
html.append(htmlEscape(field.getValue()));
html.append("</td>").append("</tr>");
}
html.append("</table>");
html.append(">");
return html.toString();
}
|
protected String getNodeLabel(GraphvizNode node) {
String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0";
StringBuilder html = new StringBuilder();
html.append("<");
html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\"");
html.append(cellborder).append("\" border=\"0\">");
html.append("<tr>").append("<td align=\"left\" port=\"header\" ");
html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">");
String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles());
if (subtitle.length() != 0) {
html.append("<font color=\"").append(node.getHeaderTextColor());
html.append("\" point-size=\"10\">");
html.append(subtitle).append("<br align=\"left\"/>").append("</font>");
}
html.append("<font color=\"" + node.getHeaderTextColor() + "\">");
html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>");
html.append("</font>").append("</td>").append("</tr>");
for (Map.Entry<String, String> field : node.getFields().entrySet()) {
html.append("<tr>");
html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">");
html.append(htmlEscape(field.getValue()));
html.append("</td>").append("</tr>");
}
html.append("</table>");
html.append(">");
return html.toString();
}
|
diff --git a/applications/secore/secore-core/src/java/secore/handler/AbstractHandler.java b/applications/secore/secore-core/src/java/secore/handler/AbstractHandler.java
index 3cc7d5e1..c5882b67 100644
--- a/applications/secore/secore-core/src/java/secore/handler/AbstractHandler.java
+++ b/applications/secore/secore-core/src/java/secore/handler/AbstractHandler.java
@@ -1,239 +1,239 @@
/*
* This file is part of rasdaman community.
*
* Rasdaman community is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rasdaman community is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with rasdaman community. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003 - 2012 Peter Baumann / rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <[email protected]>.
*/
package secore.handler;
import secore.req.ResolveResponse;
import secore.req.ResolveRequest;
import secore.db.DbManager;
import secore.util.SecoreException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import secore.req.RequestParam;
import static secore.util.Constants.*;
import secore.util.ExceptionCode;
import secore.util.StringUtil;
/**
* An abstract implementation of {@link Handler}, which provides some
* convenience methods to concrete implementations.
*
* @author Dimitar Misev
*/
public abstract class AbstractHandler implements Handler {
private static Logger log = LoggerFactory.getLogger(AbstractHandler.class);
public boolean canHandle(ResolveRequest request) throws SecoreException {
return getOperation().equals(request.getOperation());
}
/**
* Returns the parent of element <code>el</code> which text content equals
* <code>id</code>.
*
* @param el element name
* @param urnUrlPair URN/URL identifiers that should be resolved
* @param depth set the depth to which to dereference xlinks
* @param parameters parameters to substitute for target elements
* @return the definition (parent element of el)
* @throws SecoreException usually if the text content of el hasn't been matched with id
*/
protected ResolveResponse resolveId(String url, String depth, List<Parameter> parameters) throws SecoreException {
ResolveResponse ret = new ResolveResponse(resolve(IDENTIFIER_LABEL, url, depth, parameters));
if (!ret.isValidDefinition()) {
// no definition found
log.error("Failed resolving " + url);
throw new SecoreException(ExceptionCode.NoSuchDefinition, "Failed resolving " + url);
}
return ret;
}
/**
* Returns the parent of element <code>el</code> which text content equals
* <code>id</code>.
*
* @param el element name
* @param id text content to match
* @param depth set the depth to which to dereference xlinks
* @return the definition (parent element of el)
* @throws SecoreException usually if the text content of el hasn't been matched with id
*/
protected String resolve(String el, String id, String depth) throws SecoreException {
return resolve(el, id, depth, new ArrayList<Parameter>());
}
/**
* Returns the parent of element <code>el</code> which text content equals
* <code>id</code>.
*
* @param el element name
* @param id text content to match
* @param depth set the depth to which to dereference xlinks
* @param parameters parameters to substitute for target elements
* @return the definition (parent element of el)
* @throws SecoreException usually if the text content of el hasn't been matched with id
*/
protected String resolve(String el, String id, String depth, List<Parameter> parameters) throws SecoreException {
String work = null;
if (!parameters.isEmpty()) {
String targets = EMPTY;
int i = 0;
for (Parameter parameter : parameters) {
if (!targets.equals(EMPTY)) {
targets += COMMA + NEW_LINE;
}
targets += " if (exists($tmp" + parameter.getTarget() +
")) then replace value of node $tmp" + parameter.getTarget() +
- " with '" + parameter.getValue() + "' else {}";
+ " with '" + parameter.getValue() + "' else ()";
if (i++ == 0) {
targets += NEW_LINE;
}
}
work =
" for $res in local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return\n" +
" copy $tmp := $res\n" +
" modify (\n" +
targets +
" )\n" +
" return $tmp\n";
} else {
work =
" let $res := local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return $res\n";
}
// construct query
String query =
"declare namespace gml = \"" + NAMESPACE_GML + "\";\n" +
"declare namespace xlink = \"" + NAMESPACE_XLINK + "\";\n" +
"declare function local:getid($d as document-node(), $id as xs:string) as element() {\n" +
" let $ret := $d//gml:" + el + "[contains(text(), $id)]/..\n" +
" return if (empty($ret)) then\n" +
" <empty/>\n" +
" else\n" +
" $ret[last()]\n" +
"};\n" +
"declare function local:flatten($d as document-node(), $id as xs:string, $depth as xs:integer) as element()* {\n" +
" copy $el := local:getid($d, $id)\n" +
" modify\n" +
" (\n" +
" for $c in $el/*[@xlink:href]\n" +
" return if ($depth < " + depth + ") then\n" +
" replace node $c with local:flatten($d, $c/@xlink:href, $depth + 1)\n" +
" else replace node $c with $c\n" +
" )\n" +
" return $el\n" +
"};\n" +
"declare function local:work($id as xs:string) as element() {\n" +
work +
"};\n" +
"local:work('" + id + "')";
return DbManager.getInstance().getDb().query(query);
}
/**
* Returns the value of the attribute with name "identifier"
* of the element <code>el</code> which text content equals to <code>id</code>.
*
* @param el element name
* @param id text content to match
* @return the data value of the attribute
* @throws SecoreException usually if the text content of el hasn't been matched with id
*/
public String resolveAttribute(String el, String id) throws SecoreException {
String query = "declare namespace gml = \"" + NAMESPACE_GML + "\";\n"
+ "let $d := collection('" + COLLECTION_NAME + "')\n"
+ "return data($d//gml:" + el + "[text() = '" + id + "']/../@identifier)";
return DbManager.getInstance().getDb().query(query);
}
public List<String> getComponentCRSs(ResolveRequest request, int componentNo) throws SecoreException {
List<RequestParam> params = request.getParams();
// component CRS URIs
List<String> components = new ArrayList<String>();
// get the component CRSs
for (int i = 0; i < params.size(); i++) {
String key = params.get(i).key;
String val = params.get(i).val.toString();
if (val != null) {
try {
int ind = Integer.parseInt(key);
if (ind == components.size() + 1) {
// the value is a CRS reference, e.g. 1=crs_ref
checkCrsRef(val);
components.add(val);
} else {
// error
log.error("Invalid " + getOperation() + " request, expected number "
+ (components.size() + 1) + " but got " + ind);
throw new SecoreException(ExceptionCode.InvalidParameterValue,
"Invalid " + getOperation() + " request, expected number "
+ (components.size() + 1) + " but got " + ind);
}
} catch (NumberFormatException ex) {
// this is a key=value pair that needs to be added to the last component
int ind = components.size() - 1;
if (ind < 0) {
log.error("Invalid " + getOperation() + " request");
throw new SecoreException(ExceptionCode.InvalidRequest,
"Invalid " + getOperation() + " request");
}
// append to last component
String component = components.get(ind);
if (component.contains(FRAGMENT_SEPARATOR)) {
component += PAIR_SEPARATOR;
} else {
component += FRAGMENT_SEPARATOR;
}
components.set(ind, component + key + KEY_VALUE_SEPARATOR + val);
}
}
}
// they both must be specified
if (components.size() < componentNo) {
log.error("Expected at least " + componentNo + " CRSs, got " + components.size());
throw new SecoreException(ExceptionCode.MissingParameterValue,
"Expected at least " + componentNo + " CRSs, got " + components.size());
}
return components;
}
private void checkCrsRef(String crsRef) throws SecoreException {
if (!crsRef.contains(StringUtil.SERVLET_CONTEXT + "/crs")) {
log.error("Invalid " + getOperation() + " request, expected a CRS reference, but got " + crsRef);
throw new SecoreException(ExceptionCode.InvalidParameterValue,
"Invalid " + getOperation() + " request, expected a CRS reference, but got " + crsRef);
}
}
}
| true | true |
protected String resolve(String el, String id, String depth, List<Parameter> parameters) throws SecoreException {
String work = null;
if (!parameters.isEmpty()) {
String targets = EMPTY;
int i = 0;
for (Parameter parameter : parameters) {
if (!targets.equals(EMPTY)) {
targets += COMMA + NEW_LINE;
}
targets += " if (exists($tmp" + parameter.getTarget() +
")) then replace value of node $tmp" + parameter.getTarget() +
" with '" + parameter.getValue() + "' else {}";
if (i++ == 0) {
targets += NEW_LINE;
}
}
work =
" for $res in local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return\n" +
" copy $tmp := $res\n" +
" modify (\n" +
targets +
" )\n" +
" return $tmp\n";
} else {
work =
" let $res := local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return $res\n";
}
// construct query
String query =
"declare namespace gml = \"" + NAMESPACE_GML + "\";\n" +
"declare namespace xlink = \"" + NAMESPACE_XLINK + "\";\n" +
"declare function local:getid($d as document-node(), $id as xs:string) as element() {\n" +
" let $ret := $d//gml:" + el + "[contains(text(), $id)]/..\n" +
" return if (empty($ret)) then\n" +
" <empty/>\n" +
" else\n" +
" $ret[last()]\n" +
"};\n" +
"declare function local:flatten($d as document-node(), $id as xs:string, $depth as xs:integer) as element()* {\n" +
" copy $el := local:getid($d, $id)\n" +
" modify\n" +
" (\n" +
" for $c in $el/*[@xlink:href]\n" +
" return if ($depth < " + depth + ") then\n" +
" replace node $c with local:flatten($d, $c/@xlink:href, $depth + 1)\n" +
" else replace node $c with $c\n" +
" )\n" +
" return $el\n" +
"};\n" +
"declare function local:work($id as xs:string) as element() {\n" +
work +
"};\n" +
"local:work('" + id + "')";
return DbManager.getInstance().getDb().query(query);
}
|
protected String resolve(String el, String id, String depth, List<Parameter> parameters) throws SecoreException {
String work = null;
if (!parameters.isEmpty()) {
String targets = EMPTY;
int i = 0;
for (Parameter parameter : parameters) {
if (!targets.equals(EMPTY)) {
targets += COMMA + NEW_LINE;
}
targets += " if (exists($tmp" + parameter.getTarget() +
")) then replace value of node $tmp" + parameter.getTarget() +
" with '" + parameter.getValue() + "' else ()";
if (i++ == 0) {
targets += NEW_LINE;
}
}
work =
" for $res in local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return\n" +
" copy $tmp := $res\n" +
" modify (\n" +
targets +
" )\n" +
" return $tmp\n";
} else {
work =
" let $res := local:flatten(collection('" + COLLECTION_NAME + "'), $id, 0)\n" +
" return $res\n";
}
// construct query
String query =
"declare namespace gml = \"" + NAMESPACE_GML + "\";\n" +
"declare namespace xlink = \"" + NAMESPACE_XLINK + "\";\n" +
"declare function local:getid($d as document-node(), $id as xs:string) as element() {\n" +
" let $ret := $d//gml:" + el + "[contains(text(), $id)]/..\n" +
" return if (empty($ret)) then\n" +
" <empty/>\n" +
" else\n" +
" $ret[last()]\n" +
"};\n" +
"declare function local:flatten($d as document-node(), $id as xs:string, $depth as xs:integer) as element()* {\n" +
" copy $el := local:getid($d, $id)\n" +
" modify\n" +
" (\n" +
" for $c in $el/*[@xlink:href]\n" +
" return if ($depth < " + depth + ") then\n" +
" replace node $c with local:flatten($d, $c/@xlink:href, $depth + 1)\n" +
" else replace node $c with $c\n" +
" )\n" +
" return $el\n" +
"};\n" +
"declare function local:work($id as xs:string) as element() {\n" +
work +
"};\n" +
"local:work('" + id + "')";
return DbManager.getInstance().getDb().query(query);
}
|
diff --git a/console/console-war/src/main/java/org/bonitasoft/console/client/admin/organization/users/view/DeactivateUserWarningPopUp.java b/console/console-war/src/main/java/org/bonitasoft/console/client/admin/organization/users/view/DeactivateUserWarningPopUp.java
index 50a31485f..86f5470a0 100644
--- a/console/console-war/src/main/java/org/bonitasoft/console/client/admin/organization/users/view/DeactivateUserWarningPopUp.java
+++ b/console/console-war/src/main/java/org/bonitasoft/console/client/admin/organization/users/view/DeactivateUserWarningPopUp.java
@@ -1,84 +1,84 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
*
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.console.client.admin.organization.users.view;
import static org.bonitasoft.web.toolkit.client.common.i18n.AbstractI18n._;
import org.bonitasoft.console.client.admin.organization.users.action.ChangeUsersStateAction;
import org.bonitasoft.console.client.admin.organization.users.action.ChangeUsersStateAction.STATE;
import org.bonitasoft.web.toolkit.client.data.APIID;
import org.bonitasoft.web.toolkit.client.ui.Page;
import org.bonitasoft.web.toolkit.client.ui.action.ClosePopUpAction;
import org.bonitasoft.web.toolkit.client.ui.component.Button;
import org.bonitasoft.web.toolkit.client.ui.component.Paragraph;
import org.bonitasoft.web.toolkit.client.ui.component.button.ButtonAction;
import org.bonitasoft.web.toolkit.client.ui.component.containers.Container;
public class DeactivateUserWarningPopUp extends Page {
public static final String TOKEN = "deactivateuserwarningpopup";
public DeactivateUserWarningPopUp() {
// used by page factory - to be deleted when we will be able to not do a Page for a Popup
}
public DeactivateUserWarningPopUp(APIID userId) {
addParameter("id", userId.toString());
}
@Override
public void defineTitle() {
setTitle(_("Warning"));
}
@Override
public void buildView() {
addBody(warningText());
addBody(buttons());
}
private Container<Paragraph> warningText() {
Container<Paragraph> container = new Container<Paragraph>();
container.append(new Paragraph(_("You risk interrupting one or more apps.")));
container.append(new Paragraph(_("Deactivating the only user able to perform a task(s), will cause the interruption of an app(s).")));
container.append(new Paragraph(_("Before proceeding, you may want to go to the 'More' page of the app and check the actor mapping.")));
- container.append(new Paragraph(_("Are you sure you want to deactivate this user now?")));
+ container.append(new Paragraph(_("Are you sure you want to deactivate this user now ?")));
return container;
}
private Container<Button> buttons() {
Container<Button> formactions = new Container<Button>();
formactions.addClass("formactions");
formactions.append(deactivateButton(), closeButon());
return formactions;
}
private Button closeButon() {
return new Button(_("Close"), _("Close"), new ClosePopUpAction());
}
private ButtonAction deactivateButton() {
return new ButtonAction(_("Deactivate"), _("Dactivate selected user"), new ChangeUsersStateAction(getParameter("id"), STATE.DISABLED));
}
@Override
public String defineToken() {
return TOKEN;
}
}
| true | true |
private Container<Paragraph> warningText() {
Container<Paragraph> container = new Container<Paragraph>();
container.append(new Paragraph(_("You risk interrupting one or more apps.")));
container.append(new Paragraph(_("Deactivating the only user able to perform a task(s), will cause the interruption of an app(s).")));
container.append(new Paragraph(_("Before proceeding, you may want to go to the 'More' page of the app and check the actor mapping.")));
container.append(new Paragraph(_("Are you sure you want to deactivate this user now?")));
return container;
}
|
private Container<Paragraph> warningText() {
Container<Paragraph> container = new Container<Paragraph>();
container.append(new Paragraph(_("You risk interrupting one or more apps.")));
container.append(new Paragraph(_("Deactivating the only user able to perform a task(s), will cause the interruption of an app(s).")));
container.append(new Paragraph(_("Before proceeding, you may want to go to the 'More' page of the app and check the actor mapping.")));
container.append(new Paragraph(_("Are you sure you want to deactivate this user now ?")));
return container;
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/EditCategoryPaneControllerImpl.java b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/EditCategoryPaneControllerImpl.java
index 20793c38..b1603194 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/EditCategoryPaneControllerImpl.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/EditCategoryPaneControllerImpl.java
@@ -1,50 +1,50 @@
package devopsdistilled.operp.client.items.panes.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.exceptions.EntityNameExistsException;
import devopsdistilled.operp.client.items.exceptions.NullFieldException;
import devopsdistilled.operp.client.items.models.CategoryModel;
import devopsdistilled.operp.client.items.panes.EditCategoryPane;
import devopsdistilled.operp.client.items.panes.controllers.EditCategoryPaneController;
import devopsdistilled.operp.client.items.panes.models.EditCategoryPaneModel;
import devopsdistilled.operp.server.data.entity.items.Category;
public class EditCategoryPaneControllerImpl implements
EditCategoryPaneController {
@Inject
private EditCategoryPane view;
@Inject
private EditCategoryPaneModel model;
@Inject
private CategoryModel categoryModel;
@Override
public void init(Category category) {
view.init();
model.setEntity(category);
model.registerObserver(view);
}
@Override
public void validate(Category category) throws EntityNameExistsException,
NullFieldException {
if (category.getCategoryName().equalsIgnoreCase(""))
- throw new NullFieldException();
+ throw new NullFieldException("Category Name can't be empty");
if (!categoryModel.getService().isCategoryNameValidForCategory(
category.getCategoryId(), category.getCategoryName()))
- throw new EntityNameExistsException();
+ throw new EntityNameExistsException("Category Name already exists");
}
@Override
public Category save(Category category) {
return categoryModel.saveAndUpdateModel(category);
}
}
| false | true |
public void validate(Category category) throws EntityNameExistsException,
NullFieldException {
if (category.getCategoryName().equalsIgnoreCase(""))
throw new NullFieldException();
if (!categoryModel.getService().isCategoryNameValidForCategory(
category.getCategoryId(), category.getCategoryName()))
throw new EntityNameExistsException();
}
|
public void validate(Category category) throws EntityNameExistsException,
NullFieldException {
if (category.getCategoryName().equalsIgnoreCase(""))
throw new NullFieldException("Category Name can't be empty");
if (!categoryModel.getService().isCategoryNameValidForCategory(
category.getCategoryId(), category.getCategoryName()))
throw new EntityNameExistsException("Category Name already exists");
}
|
diff --git a/src/org/joval/oval/adapter/windows/FileeffectiverightsAdapter.java b/src/org/joval/oval/adapter/windows/FileeffectiverightsAdapter.java
index 0250741c..701c7b1a 100755
--- a/src/org/joval/oval/adapter/windows/FileeffectiverightsAdapter.java
+++ b/src/org/joval/oval/adapter/windows/FileeffectiverightsAdapter.java
@@ -1,379 +1,379 @@
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.oval.adapter.windows;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import oval.schemas.common.MessageLevelEnumeration;
import oval.schemas.common.MessageType;
import oval.schemas.common.OperationEnumeration;
import oval.schemas.common.SimpleDatatypeEnumeration;
import oval.schemas.definitions.core.ObjectType;
import oval.schemas.definitions.windows.Fileeffectiverights53Object;
import oval.schemas.definitions.windows.FileeffectiverightsObject;
import oval.schemas.systemcharacteristics.core.EntityItemBoolType;
import oval.schemas.systemcharacteristics.core.EntityItemStringType;
import oval.schemas.systemcharacteristics.core.FlagEnumeration;
import oval.schemas.systemcharacteristics.core.ItemType;
import oval.schemas.systemcharacteristics.core.StatusEnumeration;
import oval.schemas.systemcharacteristics.windows.FileeffectiverightsItem;
import oval.schemas.results.core.ResultEnumeration;
import org.joval.intf.io.IFile;
import org.joval.intf.io.IFileEx;
import org.joval.intf.plugin.IAdapter;
import org.joval.intf.plugin.IRequestContext;
import org.joval.intf.system.IBaseSession;
import org.joval.intf.system.ISession;
import org.joval.intf.windows.identity.IACE;
import org.joval.intf.windows.identity.IDirectory;
import org.joval.intf.windows.identity.IPrincipal;
import org.joval.intf.windows.io.IWindowsFileInfo;
import org.joval.intf.windows.system.IWindowsSession;
import org.joval.os.windows.wmi.WmiException;
import org.joval.oval.CollectException;
import org.joval.oval.Factories;
import org.joval.oval.adapter.independent.BaseFileAdapter;
import org.joval.util.JOVALMsg;
import org.joval.util.StringTools;
import org.joval.util.Version;
/**
* Collects items for Fileeffectiverights and Fileeffectiverights53 objects.
*
* @author David A. Solin
* @version %I% %G%
*/
public class FileeffectiverightsAdapter extends BaseFileAdapter<FileeffectiverightsItem> {
private IWindowsSession ws;
private IDirectory directory;
// Implement IAdapter
public Collection<Class> init(IBaseSession session) {
Collection<Class> classes = new Vector<Class>();
if (session instanceof IWindowsSession) {
super.init((ISession)session);
this.ws = (IWindowsSession)session;
classes.add(Fileeffectiverights53Object.class);
classes.add(FileeffectiverightsObject.class);
}
return classes;
}
// Protected
protected Class getItemClass() {
return FileeffectiverightsItem.class;
}
protected Collection<FileeffectiverightsItem> getItems(ObjectType obj, ItemType base, IFile f, IRequestContext rc)
throws IOException, CollectException {
//
// Grab a fresh directory in case there's been a reconnect since initialization.
//
directory = ws.getDirectory();
Collection<FileeffectiverightsItem> items = new Vector<FileeffectiverightsItem>();
FileeffectiverightsItem baseItem = null;
if (base instanceof FileeffectiverightsItem) {
baseItem = (FileeffectiverightsItem)base;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ITEM, base.getClass().getName());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
String pSid = null, pName = null;
boolean includeGroups = true;
- boolean resolveGroups = true;
+ boolean resolveGroups = false;
OperationEnumeration op = OperationEnumeration.EQUALS;
if (obj instanceof Fileeffectiverights53Object) {
Fileeffectiverights53Object fObj = (Fileeffectiverights53Object)obj;
op = fObj.getTrusteeSid().getOperation();
pSid = (String)fObj.getTrusteeSid().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else if (obj instanceof FileeffectiverightsObject) {
FileeffectiverightsObject fObj = (FileeffectiverightsObject)obj;
op = fObj.getTrusteeName().getOperation();
pName = (String)fObj.getTrusteeName().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OBJECT, obj.getClass().getName(), obj.getId());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
IFileEx info = f.getExtended();
IWindowsFileInfo wfi = null;
if (info instanceof IWindowsFileInfo) {
wfi = (IWindowsFileInfo)info;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_WINFILE_TYPE, f.getClass().getName());
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
IACE[] aces = wfi.getSecurity();
switch(op) {
case PATTERN_MATCH:
try {
Pattern p = null;
if (pSid == null) {
p = Pattern.compile(pName);
} else {
p = Pattern.compile(pSid);
}
for (int i=0; i < aces.length; i++) {
IACE ace = aces[i];
IPrincipal principal = null;
try {
if (pSid == null) {
IPrincipal temp = directory.queryPrincipalBySid(ace.getSid());
if (directory.isBuiltinUser(temp.getNetbiosName()) ||
directory.isBuiltinGroup(temp.getNetbiosName())) {
if (p.matcher(temp.getName()).find()) {
principal = temp;
}
} else {
if (p.matcher(temp.getNetbiosName()).find()) {
principal = temp;
}
}
} else {
if (p.matcher(ace.getSid()).find()) {
principal = directory.queryPrincipalBySid(ace.getSid());
}
}
if (principal != null) {
items.add(makeItem(baseItem, principal, ace));
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.WARNING);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, e.getMessage()));
rc.addMessage(msg);
}
}
} catch (PatternSyntaxException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_PATTERN, e.getMessage()));
rc.addMessage(msg);
session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
case CASE_INSENSITIVE_EQUALS:
case EQUALS:
case NOT_EQUAL:
try {
Collection<IPrincipal> principals = null;
if (pSid == null) {
principals = directory.getAllPrincipals(directory.queryPrincipal(pName), includeGroups, resolveGroups);
} else {
principals = directory.getAllPrincipals(directory.queryPrincipalBySid(pSid), includeGroups, resolveGroups);
}
for (IPrincipal principal : principals) {
for (int i=0; i < aces.length; i++) {
switch(op) {
case EQUALS:
case CASE_INSENSITIVE_EQUALS:
if (directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
case NOT_EQUAL:
if (!directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
}
}
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
if (pSid == null) {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pName));
} else {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pSid));
}
rc.addMessage(msg);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
default:
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op);
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
return items;
}
// Private
/**
* Create a new wrapped FileeffectiverightsItem based on the base FileeffectiverightsItem, IPrincipal and IACE.
*/
private FileeffectiverightsItem makeItem(FileeffectiverightsItem base, IPrincipal p, IACE ace) throws IOException {
FileeffectiverightsItem item = Factories.sc.windows.createFileeffectiverightsItem();
item.setPath(base.getPath());
item.setFilename(base.getFilename());
item.setFilepath(base.getFilepath());
item.setWindowsView(base.getWindowsView());
int accessMask = ace.getAccessMask();
boolean test = false;
test = IACE.ACCESS_SYSTEM_SECURITY == (IACE.ACCESS_SYSTEM_SECURITY | accessMask);
EntityItemBoolType accessSystemSecurity = Factories.sc.core.createEntityItemBoolType();
accessSystemSecurity.setValue(Boolean.toString(test));
accessSystemSecurity.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setAccessSystemSecurity(accessSystemSecurity);
test = IACE.FILE_APPEND_DATA == (IACE.FILE_APPEND_DATA | accessMask);
EntityItemBoolType fileAppendData = Factories.sc.core.createEntityItemBoolType();
fileAppendData.setValue(Boolean.toString(test));
fileAppendData.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileAppendData(fileAppendData);
test = IACE.FILE_DELETE == (IACE.FILE_DELETE | accessMask);
EntityItemBoolType fileDeleteChild = Factories.sc.core.createEntityItemBoolType();
fileDeleteChild.setValue(Boolean.toString(test));
fileDeleteChild.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileDeleteChild(fileDeleteChild);
test = IACE.FILE_EXECUTE == (IACE.FILE_EXECUTE | accessMask);
EntityItemBoolType fileExecute = Factories.sc.core.createEntityItemBoolType();
fileExecute.setValue(Boolean.toString(test));
fileExecute.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileExecute(fileExecute);
test = IACE.FILE_READ_ATTRIBUTES == (IACE.FILE_READ_ATTRIBUTES | accessMask);
EntityItemBoolType fileReadAttributes = Factories.sc.core.createEntityItemBoolType();
fileReadAttributes.setValue(Boolean.toString(test));
fileReadAttributes.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileReadAttributes(fileReadAttributes);
test = IACE.FILE_READ_DATA == (IACE.FILE_READ_DATA | accessMask);
EntityItemBoolType fileReadData = Factories.sc.core.createEntityItemBoolType();
fileReadData.setValue(Boolean.toString(test));
fileReadData.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileReadData(fileReadData);
test = IACE.FILE_READ_EA == (IACE.FILE_READ_EA | accessMask);
EntityItemBoolType fileReadEa = Factories.sc.core.createEntityItemBoolType();
fileReadEa.setValue(Boolean.toString(test));
fileReadEa.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileReadEa(fileReadEa);
test = IACE.FILE_WRITE_ATTRIBUTES == (IACE.FILE_WRITE_ATTRIBUTES | accessMask);
EntityItemBoolType fileWriteAttributes = Factories.sc.core.createEntityItemBoolType();
fileWriteAttributes.setValue(Boolean.toString(test));
fileWriteAttributes.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileWriteAttributes(fileWriteAttributes);
test = IACE.FILE_WRITE_DATA == (IACE.FILE_WRITE_DATA | accessMask);
EntityItemBoolType fileWriteData = Factories.sc.core.createEntityItemBoolType();
fileWriteData.setValue(Boolean.toString(test));
fileWriteData.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileWriteData(fileWriteData);
test = IACE.FILE_WRITE_EA == (IACE.FILE_WRITE_EA | accessMask);
EntityItemBoolType fileWriteEa = Factories.sc.core.createEntityItemBoolType();
fileWriteEa.setValue(Boolean.toString(test));
fileWriteEa.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setFileWriteEa(fileWriteEa);
test = IACE.GENERIC_ALL == (IACE.GENERIC_ALL | accessMask);
EntityItemBoolType genericAll = Factories.sc.core.createEntityItemBoolType();
genericAll.setValue(Boolean.toString(test));
genericAll.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setGenericAll(genericAll);
test = IACE.GENERIC_EXECUTE == (IACE.GENERIC_EXECUTE | accessMask);
EntityItemBoolType genericExecute = Factories.sc.core.createEntityItemBoolType();
genericExecute.setValue(Boolean.toString(test));
genericExecute.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setGenericExecute(genericExecute);
test = IACE.GENERIC_READ == (IACE.GENERIC_READ | accessMask);
EntityItemBoolType genericRead = Factories.sc.core.createEntityItemBoolType();
genericRead.setValue(Boolean.toString(test));
genericRead.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setGenericRead(genericRead);
test = IACE.GENERIC_WRITE == (IACE.GENERIC_WRITE | accessMask);
EntityItemBoolType genericWrite = Factories.sc.core.createEntityItemBoolType();
genericWrite.setValue(Boolean.toString(test));
genericWrite.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setGenericWrite(genericWrite);
test = IACE.STANDARD_DELETE == (IACE.STANDARD_DELETE | accessMask);
EntityItemBoolType standardDelete = Factories.sc.core.createEntityItemBoolType();
standardDelete.setValue(Boolean.toString(test));
standardDelete.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setStandardDelete(standardDelete);
test = IACE.STANDARD_READ_CONTROL == (IACE.STANDARD_READ_CONTROL | accessMask);
EntityItemBoolType standardReadControl = Factories.sc.core.createEntityItemBoolType();
standardReadControl.setValue(Boolean.toString(test));
standardReadControl.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setStandardReadControl(standardReadControl);
test = IACE.STANDARD_SYNCHRONIZE == (IACE.STANDARD_SYNCHRONIZE | accessMask);
EntityItemBoolType standardSynchronize = Factories.sc.core.createEntityItemBoolType();
standardSynchronize.setValue(Boolean.toString(test));
standardSynchronize.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setStandardSynchronize(standardSynchronize);
test = IACE.STANDARD_WRITE_DAC == (IACE.STANDARD_WRITE_DAC | accessMask);
EntityItemBoolType standardWriteDac = Factories.sc.core.createEntityItemBoolType();
standardWriteDac.setValue(Boolean.toString(test));
standardWriteDac.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setStandardWriteDac(standardWriteDac);
test = IACE.STANDARD_WRITE_OWNER == (IACE.STANDARD_WRITE_OWNER | accessMask);
EntityItemBoolType standardWriteOwner = Factories.sc.core.createEntityItemBoolType();
standardWriteOwner.setValue(Boolean.toString(test));
standardWriteOwner.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
item.setStandardWriteOwner(standardWriteOwner);
EntityItemStringType trusteeName = Factories.sc.core.createEntityItemStringType();
if (directory.isBuiltinUser(p.getNetbiosName()) || directory.isBuiltinGroup(p.getNetbiosName())) {
trusteeName.setValue(p.getName());
} else {
trusteeName.setValue(p.getNetbiosName());
}
item.setTrusteeName(trusteeName);
EntityItemStringType trusteeSid = Factories.sc.core.createEntityItemStringType();
trusteeSid.setValue(p.getSid());
item.setTrusteeSid(trusteeSid);
return item;
}
}
| true | true |
protected Collection<FileeffectiverightsItem> getItems(ObjectType obj, ItemType base, IFile f, IRequestContext rc)
throws IOException, CollectException {
//
// Grab a fresh directory in case there's been a reconnect since initialization.
//
directory = ws.getDirectory();
Collection<FileeffectiverightsItem> items = new Vector<FileeffectiverightsItem>();
FileeffectiverightsItem baseItem = null;
if (base instanceof FileeffectiverightsItem) {
baseItem = (FileeffectiverightsItem)base;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ITEM, base.getClass().getName());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
String pSid = null, pName = null;
boolean includeGroups = true;
boolean resolveGroups = true;
OperationEnumeration op = OperationEnumeration.EQUALS;
if (obj instanceof Fileeffectiverights53Object) {
Fileeffectiverights53Object fObj = (Fileeffectiverights53Object)obj;
op = fObj.getTrusteeSid().getOperation();
pSid = (String)fObj.getTrusteeSid().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else if (obj instanceof FileeffectiverightsObject) {
FileeffectiverightsObject fObj = (FileeffectiverightsObject)obj;
op = fObj.getTrusteeName().getOperation();
pName = (String)fObj.getTrusteeName().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OBJECT, obj.getClass().getName(), obj.getId());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
IFileEx info = f.getExtended();
IWindowsFileInfo wfi = null;
if (info instanceof IWindowsFileInfo) {
wfi = (IWindowsFileInfo)info;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_WINFILE_TYPE, f.getClass().getName());
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
IACE[] aces = wfi.getSecurity();
switch(op) {
case PATTERN_MATCH:
try {
Pattern p = null;
if (pSid == null) {
p = Pattern.compile(pName);
} else {
p = Pattern.compile(pSid);
}
for (int i=0; i < aces.length; i++) {
IACE ace = aces[i];
IPrincipal principal = null;
try {
if (pSid == null) {
IPrincipal temp = directory.queryPrincipalBySid(ace.getSid());
if (directory.isBuiltinUser(temp.getNetbiosName()) ||
directory.isBuiltinGroup(temp.getNetbiosName())) {
if (p.matcher(temp.getName()).find()) {
principal = temp;
}
} else {
if (p.matcher(temp.getNetbiosName()).find()) {
principal = temp;
}
}
} else {
if (p.matcher(ace.getSid()).find()) {
principal = directory.queryPrincipalBySid(ace.getSid());
}
}
if (principal != null) {
items.add(makeItem(baseItem, principal, ace));
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.WARNING);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, e.getMessage()));
rc.addMessage(msg);
}
}
} catch (PatternSyntaxException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_PATTERN, e.getMessage()));
rc.addMessage(msg);
session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
case CASE_INSENSITIVE_EQUALS:
case EQUALS:
case NOT_EQUAL:
try {
Collection<IPrincipal> principals = null;
if (pSid == null) {
principals = directory.getAllPrincipals(directory.queryPrincipal(pName), includeGroups, resolveGroups);
} else {
principals = directory.getAllPrincipals(directory.queryPrincipalBySid(pSid), includeGroups, resolveGroups);
}
for (IPrincipal principal : principals) {
for (int i=0; i < aces.length; i++) {
switch(op) {
case EQUALS:
case CASE_INSENSITIVE_EQUALS:
if (directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
case NOT_EQUAL:
if (!directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
}
}
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
if (pSid == null) {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pName));
} else {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pSid));
}
rc.addMessage(msg);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
default:
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op);
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
return items;
}
|
protected Collection<FileeffectiverightsItem> getItems(ObjectType obj, ItemType base, IFile f, IRequestContext rc)
throws IOException, CollectException {
//
// Grab a fresh directory in case there's been a reconnect since initialization.
//
directory = ws.getDirectory();
Collection<FileeffectiverightsItem> items = new Vector<FileeffectiverightsItem>();
FileeffectiverightsItem baseItem = null;
if (base instanceof FileeffectiverightsItem) {
baseItem = (FileeffectiverightsItem)base;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ITEM, base.getClass().getName());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
String pSid = null, pName = null;
boolean includeGroups = true;
boolean resolveGroups = false;
OperationEnumeration op = OperationEnumeration.EQUALS;
if (obj instanceof Fileeffectiverights53Object) {
Fileeffectiverights53Object fObj = (Fileeffectiverights53Object)obj;
op = fObj.getTrusteeSid().getOperation();
pSid = (String)fObj.getTrusteeSid().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else if (obj instanceof FileeffectiverightsObject) {
FileeffectiverightsObject fObj = (FileeffectiverightsObject)obj;
op = fObj.getTrusteeName().getOperation();
pName = (String)fObj.getTrusteeName().getValue();
if (fObj.isSetBehaviors()) {
includeGroups = fObj.getBehaviors().getIncludeGroup();
resolveGroups = fObj.getBehaviors().getResolveGroup();
}
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OBJECT, obj.getClass().getName(), obj.getId());
throw new CollectException(msg, FlagEnumeration.ERROR);
}
IFileEx info = f.getExtended();
IWindowsFileInfo wfi = null;
if (info instanceof IWindowsFileInfo) {
wfi = (IWindowsFileInfo)info;
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_WINFILE_TYPE, f.getClass().getName());
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
IACE[] aces = wfi.getSecurity();
switch(op) {
case PATTERN_MATCH:
try {
Pattern p = null;
if (pSid == null) {
p = Pattern.compile(pName);
} else {
p = Pattern.compile(pSid);
}
for (int i=0; i < aces.length; i++) {
IACE ace = aces[i];
IPrincipal principal = null;
try {
if (pSid == null) {
IPrincipal temp = directory.queryPrincipalBySid(ace.getSid());
if (directory.isBuiltinUser(temp.getNetbiosName()) ||
directory.isBuiltinGroup(temp.getNetbiosName())) {
if (p.matcher(temp.getName()).find()) {
principal = temp;
}
} else {
if (p.matcher(temp.getNetbiosName()).find()) {
principal = temp;
}
}
} else {
if (p.matcher(ace.getSid()).find()) {
principal = directory.queryPrincipalBySid(ace.getSid());
}
}
if (principal != null) {
items.add(makeItem(baseItem, principal, ace));
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.WARNING);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, e.getMessage()));
rc.addMessage(msg);
}
}
} catch (PatternSyntaxException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_PATTERN, e.getMessage()));
rc.addMessage(msg);
session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
case CASE_INSENSITIVE_EQUALS:
case EQUALS:
case NOT_EQUAL:
try {
Collection<IPrincipal> principals = null;
if (pSid == null) {
principals = directory.getAllPrincipals(directory.queryPrincipal(pName), includeGroups, resolveGroups);
} else {
principals = directory.getAllPrincipals(directory.queryPrincipalBySid(pSid), includeGroups, resolveGroups);
}
for (IPrincipal principal : principals) {
for (int i=0; i < aces.length; i++) {
switch(op) {
case EQUALS:
case CASE_INSENSITIVE_EQUALS:
if (directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
case NOT_EQUAL:
if (!directory.isApplicable(principal, aces[i])) {
items.add(makeItem(baseItem, principal, aces[i]));
}
break;
}
}
}
} catch (NoSuchElementException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
if (pSid == null) {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pName));
} else {
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINDIR_NOPRINCIPAL, pSid));
}
rc.addMessage(msg);
} catch (WmiException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_WINWMI_GENERAL, obj.getId(), e.getMessage()));
rc.addMessage(msg);
}
break;
default:
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op);
throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED);
}
return items;
}
|
diff --git a/src/org/python/modules/_threading/_threading.java b/src/org/python/modules/_threading/_threading.java
index 1a9c11bc..04838dad 100644
--- a/src/org/python/modules/_threading/_threading.java
+++ b/src/org/python/modules/_threading/_threading.java
@@ -1,15 +1,17 @@
package org.python.modules._threading;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyObject;
public class _threading implements ClassDictInit {
public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
+ dict.__setitem__("_Lock", Lock.TYPE);
+ dict.__setitem__("_RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
}
| true | true |
public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
|
public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
dict.__setitem__("_Lock", Lock.TYPE);
dict.__setitem__("_RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
|
diff --git a/orcid-web/src/main/java/org/orcid/frontend/web/controllers/PublicProfileController.java b/orcid-web/src/main/java/org/orcid/frontend/web/controllers/PublicProfileController.java
index cb6e02f1ba..7bd3bb282c 100644
--- a/orcid-web/src/main/java/org/orcid/frontend/web/controllers/PublicProfileController.java
+++ b/orcid-web/src/main/java/org/orcid/frontend/web/controllers/PublicProfileController.java
@@ -1,50 +1,51 @@
/**
* =============================================================================
*
* ORCID (R) Open Source
* http://orcid.org
*
* Copyright (c) 2012-2013 ORCID, Inc.
* Licensed under an MIT-Style License (MIT)
* http://orcid.org/open-source-license
*
* This copyright and license information (including a link to the full license)
* shall be included in its entirety in all copies or substantial portion of
* the software.
*
* =============================================================================
*/
package org.orcid.frontend.web.controllers;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.orcid.frontend.web.forms.CurrentWork;
import org.orcid.jaxb.model.message.OrcidProfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class PublicProfileController extends BaseWorkspaceController {
@RequestMapping(value = "/{orcid:(?:\\d{4}-){3,}\\d{3}[\\dX]}")
public ModelAndView publicPreview(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int pageNo,
@RequestParam(value = "maxResults", defaultValue = "15") int maxResults, @PathVariable("orcid") String orcid) {
ModelAndView mav = new ModelAndView("public_profile");
request.getSession().removeAttribute(PUBLIC_WORKS_RESULTS_ATTRIBUTE);
OrcidProfile profile = orcidProfileManager.retrievePublicOrcidProfile(orcid);
List<CurrentWork> currentWorks = getCurrentWorksFromProfile(profile);
if (currentWorks != null && !currentWorks.isEmpty()) {
mav.addObject("currentWorks", currentWorks);
}
mav.addObject("profile", profile);
mav.addObject("baseUri",getBaseUri());
+ mav.addObject("baseUriHttp",getBaseUriHttp());
return mav;
}
}
| true | true |
public ModelAndView publicPreview(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int pageNo,
@RequestParam(value = "maxResults", defaultValue = "15") int maxResults, @PathVariable("orcid") String orcid) {
ModelAndView mav = new ModelAndView("public_profile");
request.getSession().removeAttribute(PUBLIC_WORKS_RESULTS_ATTRIBUTE);
OrcidProfile profile = orcidProfileManager.retrievePublicOrcidProfile(orcid);
List<CurrentWork> currentWorks = getCurrentWorksFromProfile(profile);
if (currentWorks != null && !currentWorks.isEmpty()) {
mav.addObject("currentWorks", currentWorks);
}
mav.addObject("profile", profile);
mav.addObject("baseUri",getBaseUri());
return mav;
}
|
public ModelAndView publicPreview(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int pageNo,
@RequestParam(value = "maxResults", defaultValue = "15") int maxResults, @PathVariable("orcid") String orcid) {
ModelAndView mav = new ModelAndView("public_profile");
request.getSession().removeAttribute(PUBLIC_WORKS_RESULTS_ATTRIBUTE);
OrcidProfile profile = orcidProfileManager.retrievePublicOrcidProfile(orcid);
List<CurrentWork> currentWorks = getCurrentWorksFromProfile(profile);
if (currentWorks != null && !currentWorks.isEmpty()) {
mav.addObject("currentWorks", currentWorks);
}
mav.addObject("profile", profile);
mav.addObject("baseUri",getBaseUri());
mav.addObject("baseUriHttp",getBaseUriHttp());
return mav;
}
|
diff --git a/src/main/java/net/downwithdestruction/dwdshop/Events.java b/src/main/java/net/downwithdestruction/dwdshop/Events.java
index ed3e12c..ca3c1f7 100644
--- a/src/main/java/net/downwithdestruction/dwdshop/Events.java
+++ b/src/main/java/net/downwithdestruction/dwdshop/Events.java
@@ -1,344 +1,344 @@
package net.downwithdestruction.dwdshop;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class Events implements Listener {
public static Set<String> repairMode = new HashSet<String>();
public static Set<String> createMode = new HashSet<String>();
public Events(DwDShopPlugin plugin) {
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.getPlayer().isSneaking()) return;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
Block block = location.getBlock();
if (block.getType() == Material.SIGN
|| block.getType() == Material.WALL_SIGN
|| block.getType() == Material.SIGN_POST) {
if (repairMode.contains(event.getPlayer().getName())) {
// Convert from old format
Sign sign = (Sign) block.getState();
DwDShopPlugin.debug("Line 0:" + sign.getLine(0));
if ((sign.getLine(0).toLowerCase().contains("admin") && sign
.getLine(0).toLowerCase().contains("shop"))
|| Shops.isShop(location)) {
int amount = Integer.parseInt(sign.getLine(1));
int x, y, z;
x = location.getBlockX();
y = location.getBlockY();
z = location.getBlockZ();
Entity[] entities = location.getChunk().getEntities();
for (Entity e : entities) {
Location eLoc = e.getLocation();
if ((eLoc.getBlockX() == x)
&& (eLoc.getBlockZ()) == z
&& (eLoc.getBlockY() > y)
&& (eLoc.getBlockY() <= (y + 2))
&& (e.getType() == EntityType.ITEM_FRAME)) {
// Found the entity
ItemFrame frame = (ItemFrame) e;
int item = frame.getItem().getTypeId();
short damage = frame.getItem().getDurability();
String itemID = (damage == 0) ? "" + item
: item + ":" + damage;
// Get Prices
try {
DwDShopPlugin.debug("Query: SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
ResultSet results = DwDShopPlugin.db
.query("SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
DwDShopPlugin.debug("Found price");
double buy, sell;
buy = results.getDouble("buy");
sell = results.getDouble("sell");
// Add the local storage
Shop shop = Shops.createShop(location, item,
damage, amount, buy, sell);
shop.update();
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("signs.shopUpdated"));
} else {
// Item not found
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
break;
}
}
} else {
event.getPlayer().sendMessage(
DwDShopPlugin.lang
.get("exceptions.notAdminShop"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
} else {
if (Shops.isShop(location)) {
// Sell
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Sell Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
// Check inventory
if (player.getInventory().contains(
Material.getMaterial(shop.getItemID()), shop.getAmount())) {
double price = shop.getSell() * shop.getAmount();
short damage = (short) shop.getItemDamage();
if(damage > 0) {
itemID = itemID+":"+damage;
}
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.depositPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().removeItem(items);
player.updateInventory();
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.sellComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItems"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
} else if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
if (Shops.isShop(location)) {
// Buy
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Buy Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
short damage = (short) shop.getItemDamage();
double price = shop.getBuy() * shop.getAmount();
if(damage > 0) {
itemID = itemID+":"+damage;
}
// Check inventory
if (DwDShopPlugin.economy.has(player.getName(), price)) {
- if(player.getInventory().firstEmpty() > 0) {
+ if(player.getInventory().firstEmpty() >= 0) {
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.withdrawPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().addItem(items);
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.buyComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
}
else {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItemSpace"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughFunds"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
@EventHandler
public void onSignChange(SignChangeEvent event) {
DwDShopPlugin.debug("SignChangeEvent triggered");
if (createMode.contains(event.getPlayer().getName())) {
DwDShopPlugin.debug("Player in create mode");
Block block = event.getBlock();
Location location = block.getLocation();
if (block.getType().equals(Material.SIGN)
|| block.getType().equals(Material.WALL_SIGN)
|| block.getType().equals(Material.SIGN_POST)) {
DwDShopPlugin.debug("Block is a sign");
if (event.getLine(1).toLowerCase().contains("[shop]")) {
DwDShopPlugin.debug("Sign contains [shop]");
int amount = 1;
int x, y, z;
x = location.getBlockX();
y = location.getBlockY();
z = location.getBlockZ();
Entity[] entities = location.getChunk().getEntities();
for (Entity e : entities) {
Location eLoc = e.getLocation();
if ((eLoc.getBlockX() == x) && (eLoc.getBlockZ()) == z
&& (eLoc.getBlockY() > y)
&& (eLoc.getBlockY() <= (y + 2))
&& (e.getType() == EntityType.ITEM_FRAME)) {
// Found the entity
// Work out amount (1 or 64)
if ((eLoc.getBlockY() - location.getBlockY()) > 1) {
amount = 64;
}
ItemFrame frame = (ItemFrame) e;
int item = frame.getItem().getTypeId();
short damage = frame.getItem().getDurability();
String itemID = (damage == 0) ? "" + item : item
+ ":" + damage;
// Get Prices
try {
DwDShopPlugin
.debug("Query: SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
ResultSet results = DwDShopPlugin.db
.query("SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
DwDShopPlugin.debug("Found price");
double buy, sell;
buy = results.getDouble("buy");
sell = results.getDouble("sell");
// Add the local storage
Shop shop = Shops.createShop(location,
item, damage, amount, buy, sell);
String[] signText = shop.update();
event.setLine(0, signText[0]);
event.setLine(1, signText[1]);
event.setLine(2, signText[2]);
event.setLine(3, signText[3]);
event.getPlayer().sendMessage(
DwDShopPlugin.lang
.get("signs.shopCreated"));
} else {
// Item not found
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
break;
}
}
}
}
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Location loc = event.getBlock().getLocation();
if (Shops.isShop(loc)) {
if (event.getPlayer().hasPermission("dwdshop.shop.delete")) {
Shops.deleteShop(loc);
event.getPlayer().sendMessage(
DwDShopPlugin.lang.get("signs.shopDeleted"));
} else {
event.setCancelled(true);
event.getPlayer().sendMessage(
DwDShopPlugin.lang.get("exceptions.noPermission"));
}
}
}
}
| true | true |
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.getPlayer().isSneaking()) return;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
Block block = location.getBlock();
if (block.getType() == Material.SIGN
|| block.getType() == Material.WALL_SIGN
|| block.getType() == Material.SIGN_POST) {
if (repairMode.contains(event.getPlayer().getName())) {
// Convert from old format
Sign sign = (Sign) block.getState();
DwDShopPlugin.debug("Line 0:" + sign.getLine(0));
if ((sign.getLine(0).toLowerCase().contains("admin") && sign
.getLine(0).toLowerCase().contains("shop"))
|| Shops.isShop(location)) {
int amount = Integer.parseInt(sign.getLine(1));
int x, y, z;
x = location.getBlockX();
y = location.getBlockY();
z = location.getBlockZ();
Entity[] entities = location.getChunk().getEntities();
for (Entity e : entities) {
Location eLoc = e.getLocation();
if ((eLoc.getBlockX() == x)
&& (eLoc.getBlockZ()) == z
&& (eLoc.getBlockY() > y)
&& (eLoc.getBlockY() <= (y + 2))
&& (e.getType() == EntityType.ITEM_FRAME)) {
// Found the entity
ItemFrame frame = (ItemFrame) e;
int item = frame.getItem().getTypeId();
short damage = frame.getItem().getDurability();
String itemID = (damage == 0) ? "" + item
: item + ":" + damage;
// Get Prices
try {
DwDShopPlugin.debug("Query: SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
ResultSet results = DwDShopPlugin.db
.query("SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
DwDShopPlugin.debug("Found price");
double buy, sell;
buy = results.getDouble("buy");
sell = results.getDouble("sell");
// Add the local storage
Shop shop = Shops.createShop(location, item,
damage, amount, buy, sell);
shop.update();
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("signs.shopUpdated"));
} else {
// Item not found
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
break;
}
}
} else {
event.getPlayer().sendMessage(
DwDShopPlugin.lang
.get("exceptions.notAdminShop"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
} else {
if (Shops.isShop(location)) {
// Sell
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Sell Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
// Check inventory
if (player.getInventory().contains(
Material.getMaterial(shop.getItemID()), shop.getAmount())) {
double price = shop.getSell() * shop.getAmount();
short damage = (short) shop.getItemDamage();
if(damage > 0) {
itemID = itemID+":"+damage;
}
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.depositPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().removeItem(items);
player.updateInventory();
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.sellComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItems"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
} else if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
if (Shops.isShop(location)) {
// Buy
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Buy Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
short damage = (short) shop.getItemDamage();
double price = shop.getBuy() * shop.getAmount();
if(damage > 0) {
itemID = itemID+":"+damage;
}
// Check inventory
if (DwDShopPlugin.economy.has(player.getName(), price)) {
if(player.getInventory().firstEmpty() > 0) {
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.withdrawPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().addItem(items);
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.buyComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
}
else {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItemSpace"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughFunds"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
|
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.getPlayer().isSneaking()) return;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
Block block = location.getBlock();
if (block.getType() == Material.SIGN
|| block.getType() == Material.WALL_SIGN
|| block.getType() == Material.SIGN_POST) {
if (repairMode.contains(event.getPlayer().getName())) {
// Convert from old format
Sign sign = (Sign) block.getState();
DwDShopPlugin.debug("Line 0:" + sign.getLine(0));
if ((sign.getLine(0).toLowerCase().contains("admin") && sign
.getLine(0).toLowerCase().contains("shop"))
|| Shops.isShop(location)) {
int amount = Integer.parseInt(sign.getLine(1));
int x, y, z;
x = location.getBlockX();
y = location.getBlockY();
z = location.getBlockZ();
Entity[] entities = location.getChunk().getEntities();
for (Entity e : entities) {
Location eLoc = e.getLocation();
if ((eLoc.getBlockX() == x)
&& (eLoc.getBlockZ()) == z
&& (eLoc.getBlockY() > y)
&& (eLoc.getBlockY() <= (y + 2))
&& (e.getType() == EntityType.ITEM_FRAME)) {
// Found the entity
ItemFrame frame = (ItemFrame) e;
int item = frame.getItem().getTypeId();
short damage = frame.getItem().getDurability();
String itemID = (damage == 0) ? "" + item
: item + ":" + damage;
// Get Prices
try {
DwDShopPlugin.debug("Query: SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
ResultSet results = DwDShopPlugin.db
.query("SELECT `buy`,`sell`,`itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
DwDShopPlugin.debug("Found price");
double buy, sell;
buy = results.getDouble("buy");
sell = results.getDouble("sell");
// Add the local storage
Shop shop = Shops.createShop(location, item,
damage, amount, buy, sell);
shop.update();
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("signs.shopUpdated"));
} else {
// Item not found
event.getPlayer()
.sendMessage(
DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
break;
}
}
} else {
event.getPlayer().sendMessage(
DwDShopPlugin.lang
.get("exceptions.notAdminShop"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
} else {
if (Shops.isShop(location)) {
// Sell
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Sell Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
// Check inventory
if (player.getInventory().contains(
Material.getMaterial(shop.getItemID()), shop.getAmount())) {
double price = shop.getSell() * shop.getAmount();
short damage = (short) shop.getItemDamage();
if(damage > 0) {
itemID = itemID+":"+damage;
}
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.depositPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().removeItem(items);
player.updateInventory();
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.sellComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItems"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
} else if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
if (Shops.isShop(location)) {
// Buy
Player player = event.getPlayer();
Shop shop = Shops.getShop(location);
DwDShopPlugin.debug("Buy Request "+shop.getAmount()+" of "+shop.getItemID()+":"+shop.getItemDamage()+" for "+shop.getBuy());
String itemID = ""+shop.getItemID();
short damage = (short) shop.getItemDamage();
double price = shop.getBuy() * shop.getAmount();
if(damage > 0) {
itemID = itemID+":"+damage;
}
// Check inventory
if (DwDShopPlugin.economy.has(player.getName(), price)) {
if(player.getInventory().firstEmpty() >= 0) {
ResultSet results;
try {
DwDShopPlugin.debug("Query: SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
results = DwDShopPlugin.db
.query("SELECT `itemName` FROM `Items` WHERE `itemID`='"
+ itemID + "' LIMIT 1");
if (results.first()) {
// Take ze items & ze moneh
DwDShopPlugin.economy.withdrawPlayer(
player.getName(), price);
ItemStack items = new ItemStack(
shop.getItemID(), shop.getAmount(), damage);
player.getInventory().addItem(items);
// Done \o/
String itemName = results
.getString("itemName");
player.sendMessage(DwDShopPlugin.lang
.get("signs.buyComplete")
.replaceAll("%I", itemName)
.replaceAll("%P", "" + price)
.replaceAll("%A", "" + shop.getAmount()));
}
} catch (SQLException e) {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.itemNotFound"));
}
}
else {
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughItemSpace"));
}
} else {
// Not enough items
player.sendMessage(DwDShopPlugin.lang
.get("exceptions.notEnoughFunds"));
}
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
|
diff --git a/src/flickr/Connexion.java b/src/flickr/Connexion.java
index 46b9e77..eeccd2a 100644
--- a/src/flickr/Connexion.java
+++ b/src/flickr/Connexion.java
@@ -1,56 +1,56 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package flickr;
import org.apache.http.client.methods.HttpGet;
/**
*
* @author peixoton
*/
public class Connexion {
private String login;
private String password;
public static final String KEY = "5ba9bb9bbac0804efaccd0f9d5b4b756";
public static final String SECRET_KEY = "d44f09102f60a452";
public Connexion(String login, String password){
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
if(this.login.length() > 0)
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if(this.password.length() > 0)
this.password = password;
}
@Override
public String toString(){
return "Login/Mot de passe : " + this.login + "/" + this.password;
}
- public void login() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{
+ public void login(){
//OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Connexion.KEY, Connexion.SECRET_KEY);
//consumer.setTokenWithSecret(accessToekn, accessSecret);
//HttpGet request = new HttpGet();
//consumer.sign(request);
}
}
| true | true |
public void login() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{
//OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Connexion.KEY, Connexion.SECRET_KEY);
//consumer.setTokenWithSecret(accessToekn, accessSecret);
//HttpGet request = new HttpGet();
//consumer.sign(request);
}
|
public void login(){
//OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Connexion.KEY, Connexion.SECRET_KEY);
//consumer.setTokenWithSecret(accessToekn, accessSecret);
//HttpGet request = new HttpGet();
//consumer.sign(request);
}
|
diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java
index 4924bc6543..8f27d2a1e3 100644
--- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java
+++ b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java
@@ -1,158 +1,158 @@
/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.serviceruntime;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
*
*/
class XmlRoleEnvironmentDataDeserializer implements RoleEnvironmentDataDeserializer {
public XmlRoleEnvironmentDataDeserializer() {
}
@Override
public RoleEnvironmentData deserialize(InputStream stream) {
try {
JAXBContext context = JAXBContext.newInstance(RoleEnvironmentInfo.class.getPackage().getName());
Unmarshaller unmarshaller = context.createUnmarshaller();
@SuppressWarnings("unchecked")
RoleEnvironmentInfo environmentInfo = ((JAXBElement<RoleEnvironmentInfo>) unmarshaller.unmarshal(stream))
.getValue();
Map<String, String> configurationSettings = translateConfigurationSettings(environmentInfo);
Map<String, LocalResource> localResources = translateLocalResources(environmentInfo);
RoleInstance currentInstance = translateCurrentInstance(environmentInfo);
Map<String, Role> roles = translateRoles(environmentInfo, currentInstance, environmentInfo
.getCurrentInstance().getRoleName());
return new RoleEnvironmentData(environmentInfo.getDeployment().getId(), configurationSettings,
localResources, currentInstance, roles, environmentInfo.getDeployment().isEmulated());
}
catch (JAXBException e) {
throw new RuntimeException(e);
}
}
private Map<String, String> translateConfigurationSettings(RoleEnvironmentInfo environmentInfo) {
Map<String, String> configurationSettings = new HashMap<String, String>();
for (ConfigurationSettingInfo settingInfo : environmentInfo.getCurrentInstance().getConfigurationSettings()
.getConfigurationSetting()) {
configurationSettings.put(settingInfo.getName(), settingInfo.getValue());
}
return configurationSettings;
}
private Map<String, LocalResource> translateLocalResources(RoleEnvironmentInfo environmentInfo) {
Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();
for (LocalResourceInfo resourceInfo : environmentInfo.getCurrentInstance().getLocalResources()
.getLocalResource()) {
localResources.put(resourceInfo.getName(),
new LocalResource(resourceInfo.getSizeInMB(), resourceInfo.getName(), resourceInfo.getPath()));
}
return localResources;
}
private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance,
String currentRole) {
Map<String, Role> roles = new HashMap<String, Role>();
for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) {
Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances());
- if (roleInfo.getName() == currentRole) {
+ if (roleInfo.getName().equals(currentRole)) {
instances.put(currentInstance.getId(), currentInstance);
}
Role role = new Role(roleInfo.getName(), instances);
for (RoleInstance instance : role.getInstances().values()) {
instance.setRole(role);
}
roles.put(roleInfo.getName(), role);
}
if (!roles.containsKey(currentRole)) {
Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>();
instances.put(currentInstance.getId(), currentInstance);
Role singleRole = new Role(currentRole, instances);
currentInstance.setRole(singleRole);
roles.put(currentRole, singleRole);
}
return roles;
}
private Map<String, RoleInstance> translateRoleInstances(RoleInstancesInfo instancesInfo) {
Map<String, RoleInstance> roleInstances = new HashMap<String, RoleInstance>();
for (RoleInstanceInfo instanceInfo : instancesInfo.getInstance()) {
RoleInstance instance = new RoleInstance(instanceInfo.getId(), instanceInfo.getFaultDomain(),
instanceInfo.getUpdateDomain(), translateRoleInstanceEndpoints(instanceInfo.getEndpoints()));
for (RoleInstanceEndpoint endpoint : instance.getInstanceEndpoints().values()) {
endpoint.setRoleInstance(instance);
}
roleInstances.put(instance.getId(), instance);
}
return roleInstances;
}
private Map<String, RoleInstanceEndpoint> translateRoleInstanceEndpoints(EndpointsInfo endpointsInfo) {
Map<String, RoleInstanceEndpoint> endpoints = new HashMap<String, RoleInstanceEndpoint>();
for (EndpointInfo endpointInfo : endpointsInfo.getEndpoint()) {
RoleInstanceEndpoint endpoint = new RoleInstanceEndpoint(endpointInfo.getProtocol().toString(),
new InetSocketAddress(endpointInfo.getAddress(), endpointInfo.getPort()));
endpoints.put(endpointInfo.getName(), endpoint);
}
return endpoints;
}
private RoleInstance translateCurrentInstance(RoleEnvironmentInfo environmentInfo) {
CurrentRoleInstanceInfo currentInstanceInfo = environmentInfo.getCurrentInstance();
RoleInstance currentInstance = new RoleInstance(currentInstanceInfo.getId(),
currentInstanceInfo.getFaultDomain(), currentInstanceInfo.getUpdateDomain(),
translateRoleInstanceEndpoints(environmentInfo.getCurrentInstance().getEndpoints()));
for (RoleInstanceEndpoint endpoint : currentInstance.getInstanceEndpoints().values()) {
endpoint.setRoleInstance(currentInstance);
}
return currentInstance;
}
}
| true | true |
private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance,
String currentRole) {
Map<String, Role> roles = new HashMap<String, Role>();
for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) {
Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances());
if (roleInfo.getName() == currentRole) {
instances.put(currentInstance.getId(), currentInstance);
}
Role role = new Role(roleInfo.getName(), instances);
for (RoleInstance instance : role.getInstances().values()) {
instance.setRole(role);
}
roles.put(roleInfo.getName(), role);
}
if (!roles.containsKey(currentRole)) {
Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>();
instances.put(currentInstance.getId(), currentInstance);
Role singleRole = new Role(currentRole, instances);
currentInstance.setRole(singleRole);
roles.put(currentRole, singleRole);
}
return roles;
}
|
private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance,
String currentRole) {
Map<String, Role> roles = new HashMap<String, Role>();
for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) {
Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances());
if (roleInfo.getName().equals(currentRole)) {
instances.put(currentInstance.getId(), currentInstance);
}
Role role = new Role(roleInfo.getName(), instances);
for (RoleInstance instance : role.getInstances().values()) {
instance.setRole(role);
}
roles.put(roleInfo.getName(), role);
}
if (!roles.containsKey(currentRole)) {
Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>();
instances.put(currentInstance.getId(), currentInstance);
Role singleRole = new Role(currentRole, instances);
currentInstance.setRole(singleRole);
roles.put(currentRole, singleRole);
}
return roles;
}
|
diff --git a/main/java/de/jskat/gui/table/SkatListTableModel.java b/main/java/de/jskat/gui/table/SkatListTableModel.java
index 964f48f2..e803aa05 100644
--- a/main/java/de/jskat/gui/table/SkatListTableModel.java
+++ b/main/java/de/jskat/gui/table/SkatListTableModel.java
@@ -1,303 +1,299 @@
/*
@ShortLicense@
Authors: @JS@
@MJL@
Released: @ReleaseDate@
*/
package de.jskat.gui.table;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import de.jskat.util.JSkatResourceBundle;
import de.jskat.util.Player;
import de.jskat.util.SkatConstants;
import de.jskat.util.SkatListMode;
/**
* Provides a model for the skat list table
*/
class SkatListTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private JSkatResourceBundle strings;
private SkatListMode mode = SkatListMode.NORMAL;
private int playerCount = 3;
private List<Player> declarers;
private List<List<Integer>> playerResults;
private List<Integer> gameResults;
private List<String> columns;
private List<List<Integer>> displayValues;
/**
* Constructor
*/
public SkatListTableModel() {
strings = JSkatResourceBundle.instance();
declarers = new ArrayList<Player>();
playerResults = new ArrayList<List<Integer>>();
gameResults = new ArrayList<Integer>();
displayValues = new ArrayList<List<Integer>>();
columns = new ArrayList<String>();
setColumns();
}
/**
* @see AbstractTableModel#getColumnCount()
*/
@Override
public int getColumnCount() {
return columns.size();
}
/**
* @see AbstractTableModel#getRowCount()
*/
@Override
public int getRowCount() {
return declarers.size();
}
/**
* @see AbstractTableModel#getValueAt(int, int)
*/
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object result = null;
if (displayValues.get(rowIndex).get(columnIndex) != null) {
result = displayValues.get(rowIndex).get(columnIndex);
} else {
result = "-"; //$NON-NLS-1$
}
return result;
}
Integer getPlayerValue(int playerColumn, int gameRow) {
Integer result = null;
return result;
}
/**
* @see AbstractTableModel#getColumnName(int)
*/
@Override
public String getColumnName(int col) {
return columns.get(col);
}
/**
* @see AbstractTableModel#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int col) {
return Integer.class;
}
/**
* Sets the skat list mode
*
* @param newMode
*/
void setSkatListMode(SkatListMode newMode) {
mode = newMode;
calculateDisplayValues();
fireTableDataChanged();
}
void calculateDisplayValues() {
int currResult = 0;
List<Integer> playerResultsSoFar = new ArrayList<Integer>();
+ for (int i = 0; i < playerCount; i++) {
+ playerResultsSoFar.add(new Integer(0));
+ }
displayValues.clear();
for (int game = 0; game < gameResults.size(); game++) {
displayValues.add(new ArrayList<Integer>());
// add player values
for (int player = 0; player < playerCount; player++) {
int previousResult = 0;
currResult = 0;
if (declarers.get(game) != null) {
- if (game == 0) {
- // set previous player result to 0
- playerResultsSoFar.add(new Integer(0));
- } else {
- // get previous result for player values
- // from second game on
- previousResult = playerResultsSoFar.get(player)
- .intValue();
- }
+ // get previous result for player values
+ previousResult = playerResultsSoFar.get(player).intValue();
// get player results from current game
switch (mode) {
case NORMAL:
currResult = playerResults.get(player).get(game);
break;
case TOURNAMENT:
boolean isDeclarer = (playerResults.get(player).get(
game) != 0);
currResult = SkatConstants.getTournamentGameValue(
isDeclarer, gameResults.get(game), playerCount);
break;
case BIERLACHS:
// FIXME jan 31.05.2010 add bierlachs value
break;
}
}
if (currResult != 0) {
Integer newResult = new Integer(previousResult + currResult);
displayValues.get(game).add(newResult);
playerResultsSoFar.set(player, newResult);
} else {
displayValues.get(game).add(null);
}
}
// get game result
switch (mode) {
case NORMAL:
case BIERLACHS:
currResult = gameResults.get(game);
break;
case TOURNAMENT:
currResult = SkatConstants.getTournamentGameValue(true,
gameResults.get(game), playerCount);
break;
}
displayValues.get(game).add(currResult);
}
}
/**
* Adds a game result to the model
*
* @param leftOpponent
* Position of the upper left opponent
* @param rightOpponent
* Position of the upper right opponent
* @param player
* Position of the player
* @param declarer
* Position of the game declarer
* @param gameResult
* Game result
*/
void addResult(Player leftOpponent, Player rightOpponent, Player player,
Player declarer, int gameResult) {
// FIXME works only on 3 player series
declarers.add(declarer);
gameResults.add(new Integer(gameResult));
int declarerColumn = getDeclarerColumn(leftOpponent, rightOpponent,
player, declarer);
if (declarer != null) {
playerResults.get(declarerColumn).add(new Integer(gameResult));
playerResults.get((declarerColumn + 1) % 3).add(new Integer(0));
playerResults.get((declarerColumn + 2) % 3).add(new Integer(0));
} else {
// game was passed in
for (int i = 0; i < playerCount; i++) {
playerResults.get(i).add(0);
}
}
calculateDisplayValues();
fireTableDataChanged();
}
int getDeclarerColumn(Player leftOpponent, Player rightOpponent,
Player player, Player declarer) {
int result = -1;
if (declarer == leftOpponent) {
result = 0;
} else if (declarer == rightOpponent) {
result = 1;
} else if (declarer == player) {
result = 2;
}
return result;
}
/**
* Clears the complete list
*/
void clearList() {
declarers.clear();
for (List<Integer> currList : playerResults) {
currList.clear();
}
gameResults.clear();
displayValues.clear();
fireTableDataChanged();
}
public void setPlayerCount(int newPlayerCount) {
declarers.clear();
gameResults.clear();
playerCount = newPlayerCount;
setColumns();
fireTableStructureChanged();
fireTableDataChanged();
}
void setColumns() {
playerResults.clear();
displayValues.clear();
columns.clear();
for (int i = 0; i < playerCount; i++) {
// FIXME (jan 14.12.2010) get player names
columns.add("P" + i);
playerResults.add(new ArrayList<Integer>());
displayValues.add(new ArrayList<Integer>());
}
columns.add(strings.getString("games")); //$NON-NLS-1$
displayValues.add(new ArrayList<Integer>());
}
}
| false | true |
void calculateDisplayValues() {
int currResult = 0;
List<Integer> playerResultsSoFar = new ArrayList<Integer>();
displayValues.clear();
for (int game = 0; game < gameResults.size(); game++) {
displayValues.add(new ArrayList<Integer>());
// add player values
for (int player = 0; player < playerCount; player++) {
int previousResult = 0;
currResult = 0;
if (declarers.get(game) != null) {
if (game == 0) {
// set previous player result to 0
playerResultsSoFar.add(new Integer(0));
} else {
// get previous result for player values
// from second game on
previousResult = playerResultsSoFar.get(player)
.intValue();
}
// get player results from current game
switch (mode) {
case NORMAL:
currResult = playerResults.get(player).get(game);
break;
case TOURNAMENT:
boolean isDeclarer = (playerResults.get(player).get(
game) != 0);
currResult = SkatConstants.getTournamentGameValue(
isDeclarer, gameResults.get(game), playerCount);
break;
case BIERLACHS:
// FIXME jan 31.05.2010 add bierlachs value
break;
}
}
if (currResult != 0) {
Integer newResult = new Integer(previousResult + currResult);
displayValues.get(game).add(newResult);
playerResultsSoFar.set(player, newResult);
} else {
displayValues.get(game).add(null);
}
}
// get game result
switch (mode) {
case NORMAL:
case BIERLACHS:
currResult = gameResults.get(game);
break;
case TOURNAMENT:
currResult = SkatConstants.getTournamentGameValue(true,
gameResults.get(game), playerCount);
break;
}
displayValues.get(game).add(currResult);
}
}
|
void calculateDisplayValues() {
int currResult = 0;
List<Integer> playerResultsSoFar = new ArrayList<Integer>();
for (int i = 0; i < playerCount; i++) {
playerResultsSoFar.add(new Integer(0));
}
displayValues.clear();
for (int game = 0; game < gameResults.size(); game++) {
displayValues.add(new ArrayList<Integer>());
// add player values
for (int player = 0; player < playerCount; player++) {
int previousResult = 0;
currResult = 0;
if (declarers.get(game) != null) {
// get previous result for player values
previousResult = playerResultsSoFar.get(player).intValue();
// get player results from current game
switch (mode) {
case NORMAL:
currResult = playerResults.get(player).get(game);
break;
case TOURNAMENT:
boolean isDeclarer = (playerResults.get(player).get(
game) != 0);
currResult = SkatConstants.getTournamentGameValue(
isDeclarer, gameResults.get(game), playerCount);
break;
case BIERLACHS:
// FIXME jan 31.05.2010 add bierlachs value
break;
}
}
if (currResult != 0) {
Integer newResult = new Integer(previousResult + currResult);
displayValues.get(game).add(newResult);
playerResultsSoFar.set(player, newResult);
} else {
displayValues.get(game).add(null);
}
}
// get game result
switch (mode) {
case NORMAL:
case BIERLACHS:
currResult = gameResults.get(game);
break;
case TOURNAMENT:
currResult = SkatConstants.getTournamentGameValue(true,
gameResults.get(game), playerCount);
break;
}
displayValues.get(game).add(currResult);
}
}
|
diff --git a/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java b/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java
index 81b766a4..eacc9278 100644
--- a/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java
+++ b/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java
@@ -1,186 +1,186 @@
/*
* Copyright (C) 2011 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.trebuchet.preference;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.NumberPicker;
import com.cyanogenmod.trebuchet.R;
/*
* @author Danesh
* @author nebkat
*/
public class DoubleNumberPickerPreference extends DialogPreference {
private int mMin1, mMax1, mDefault1;
private int mMin2, mMax2, mDefault2;
private String mMaxExternalKey1, mMinExternalKey1;
private String mMaxExternalKey2, mMinExternalKey2;
private String mPickerTitle1;
private String mPickerTitle2;
private NumberPicker mNumberPicker1;
private NumberPicker mNumberPicker2;
public DoubleNumberPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray dialogType = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.DialogPreference, 0, 0);
TypedArray doubleNumberPickerType = context.obtainStyledAttributes(attrs,
R.styleable.DoubleNumberPickerPreference, 0, 0);
mMaxExternalKey1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_maxExternal1);
mMinExternalKey1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_minExternal1);
mMaxExternalKey2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_maxExternal2);
mMinExternalKey2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_minExternal2);
mPickerTitle1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_pickerTitle1);
mPickerTitle2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_pickerTitle2);
mMax1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_max1, 5);
mMin1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_min1, 0);
mMax2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_max2, 5);
mMin2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_min2, 0);
mDefault1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_defaultValue1, mMin1);
mDefault2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_defaultValue2, mMin2);
dialogType.recycle();
doubleNumberPickerType.recycle();
}
@Override
protected View onCreateDialogView() {
int max1 = mMax1;
int min1 = mMin1;
int max2 = mMax2;
int min2 = mMin2;
// External values
if (mMaxExternalKey1 != null) {
max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1);
}
if (mMinExternalKey1 != null) {
min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1);
}
if (mMaxExternalKey2 != null) {
max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2);
}
if (mMinExternalKey2 != null) {
min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2);
}
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.double_number_picker_dialog, null);
mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1);
mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2);
if (mNumberPicker1 == null || mNumberPicker2 == null) {
throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!");
}
// Initialize state
- mNumberPicker1.setWrapSelectorWheel(false);
mNumberPicker1.setMaxValue(max1);
mNumberPicker1.setMinValue(min1);
mNumberPicker1.setValue(getPersistedValue(1));
- mNumberPicker2.setWrapSelectorWheel(false);
+ mNumberPicker1.setWrapSelectorWheel(false);
mNumberPicker2.setMaxValue(max2);
mNumberPicker2.setMinValue(min2);
mNumberPicker2.setValue(getPersistedValue(2));
+ mNumberPicker2.setWrapSelectorWheel(false);
// Titles
TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1);
TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2);
if (pickerTitle1 != null && pickerTitle2 != null) {
pickerTitle1.setText(mPickerTitle1);
pickerTitle2.setText(mPickerTitle2);
}
// No keyboard popup
EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input);
EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input);
if (textInput1 != null && textInput2 != null) {
textInput1.setCursorVisible(false);
textInput1.setFocusable(false);
textInput1.setFocusableInTouchMode(false);
textInput2.setCursorVisible(false);
textInput2.setFocusable(false);
textInput2.setFocusableInTouchMode(false);
}
return view;
}
private int getPersistedValue(int value) {
String[] values = getPersistedString(mDefault1 + "|" + mDefault2).split("\\|");
if (value == 1) {
try {
return Integer.parseInt(values[0]);
} catch (NumberFormatException e) {
return mDefault1;
}
} else {
try {
return Integer.parseInt(values[1]);
} catch (NumberFormatException e) {
return mDefault2;
}
}
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
persistString(mNumberPicker1.getValue() + "|" + mNumberPicker2.getValue());
}
}
public void setMin1(int min) {
mMin1 = min;
}
public void setMax1(int max) {
mMax1 = max;
}
public void setMin2(int min) {
mMin2 = min;
}
public void setMax2(int max) {
mMax2 = max;
}
public void setDefault1(int def) {
mDefault1 = def;
}
public void setDefault2(int def) {
mDefault2 = def;
}
}
| false | true |
protected View onCreateDialogView() {
int max1 = mMax1;
int min1 = mMin1;
int max2 = mMax2;
int min2 = mMin2;
// External values
if (mMaxExternalKey1 != null) {
max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1);
}
if (mMinExternalKey1 != null) {
min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1);
}
if (mMaxExternalKey2 != null) {
max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2);
}
if (mMinExternalKey2 != null) {
min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2);
}
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.double_number_picker_dialog, null);
mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1);
mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2);
if (mNumberPicker1 == null || mNumberPicker2 == null) {
throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!");
}
// Initialize state
mNumberPicker1.setWrapSelectorWheel(false);
mNumberPicker1.setMaxValue(max1);
mNumberPicker1.setMinValue(min1);
mNumberPicker1.setValue(getPersistedValue(1));
mNumberPicker2.setWrapSelectorWheel(false);
mNumberPicker2.setMaxValue(max2);
mNumberPicker2.setMinValue(min2);
mNumberPicker2.setValue(getPersistedValue(2));
// Titles
TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1);
TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2);
if (pickerTitle1 != null && pickerTitle2 != null) {
pickerTitle1.setText(mPickerTitle1);
pickerTitle2.setText(mPickerTitle2);
}
// No keyboard popup
EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input);
EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input);
if (textInput1 != null && textInput2 != null) {
textInput1.setCursorVisible(false);
textInput1.setFocusable(false);
textInput1.setFocusableInTouchMode(false);
textInput2.setCursorVisible(false);
textInput2.setFocusable(false);
textInput2.setFocusableInTouchMode(false);
}
return view;
}
|
protected View onCreateDialogView() {
int max1 = mMax1;
int min1 = mMin1;
int max2 = mMax2;
int min2 = mMin2;
// External values
if (mMaxExternalKey1 != null) {
max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1);
}
if (mMinExternalKey1 != null) {
min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1);
}
if (mMaxExternalKey2 != null) {
max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2);
}
if (mMinExternalKey2 != null) {
min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2);
}
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.double_number_picker_dialog, null);
mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1);
mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2);
if (mNumberPicker1 == null || mNumberPicker2 == null) {
throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!");
}
// Initialize state
mNumberPicker1.setMaxValue(max1);
mNumberPicker1.setMinValue(min1);
mNumberPicker1.setValue(getPersistedValue(1));
mNumberPicker1.setWrapSelectorWheel(false);
mNumberPicker2.setMaxValue(max2);
mNumberPicker2.setMinValue(min2);
mNumberPicker2.setValue(getPersistedValue(2));
mNumberPicker2.setWrapSelectorWheel(false);
// Titles
TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1);
TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2);
if (pickerTitle1 != null && pickerTitle2 != null) {
pickerTitle1.setText(mPickerTitle1);
pickerTitle2.setText(mPickerTitle2);
}
// No keyboard popup
EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input);
EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input);
if (textInput1 != null && textInput2 != null) {
textInput1.setCursorVisible(false);
textInput1.setFocusable(false);
textInput1.setFocusableInTouchMode(false);
textInput2.setCursorVisible(false);
textInput2.setFocusable(false);
textInput2.setFocusableInTouchMode(false);
}
return view;
}
|
diff --git a/public/java/src/org/broadinstitute/sting/commandline/ArgumentTypeDescriptor.java b/public/java/src/org/broadinstitute/sting/commandline/ArgumentTypeDescriptor.java
index b54e7c7b1..d1d9cf7fe 100644
--- a/public/java/src/org/broadinstitute/sting/commandline/ArgumentTypeDescriptor.java
+++ b/public/java/src/org/broadinstitute/sting/commandline/ArgumentTypeDescriptor.java
@@ -1,760 +1,760 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.commandline;
import org.apache.log4j.Logger;
import org.broad.tribble.Feature;
import org.broadinstitute.sting.gatk.refdata.tracks.FeatureManager;
import org.broadinstitute.sting.gatk.walkers.Multiplex;
import org.broadinstitute.sting.gatk.walkers.Multiplexer;
import org.broadinstitute.sting.utils.classloader.JVMUtils;
import org.broadinstitute.sting.utils.exceptions.DynamicClassResolutionException;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
/**
* An descriptor capable of providing parsers that can parse any type
* of supported command-line argument.
*
* @author mhanna
* @version 0.1
*/
public abstract class ArgumentTypeDescriptor {
private static Class[] ARGUMENT_ANNOTATIONS = {Input.class, Output.class, Argument.class};
/**
* our log, which we want to capture anything from org.broadinstitute.sting
*/
protected static Logger logger = Logger.getLogger(ArgumentTypeDescriptor.class);
/**
* Fetch the given descriptor from the descriptor repository.
* @param descriptors the descriptors from which to select a good match.
* @param type Class for which to specify a descriptor.
* @return descriptor for the given type.
*/
public static ArgumentTypeDescriptor selectBest( Collection<ArgumentTypeDescriptor> descriptors, Class type ) {
for( ArgumentTypeDescriptor descriptor: descriptors ) {
if( descriptor.supports(type) )
return descriptor;
}
throw new ReviewedStingException("Can't process command-line arguments of type: " + type.getName());
}
/**
* Does this descriptor support classes of the given type?
* @param type The type to check.
* @return true if this descriptor supports the given type, false otherwise.
*/
public abstract boolean supports( Class type );
/**
* Returns false if a type-specific default can be employed.
* @param source Source of the command-line argument.
* @return True to throw in a type specific default. False otherwise.
*/
public boolean createsTypeDefault(ArgumentSource source) { return false; }
/**
* Returns a documentation-friendly value for the default of a type descriptor.
* Must be overridden if createsTypeDefault return true. cannot be called otherwise
* @param source Source of the command-line argument.
* @return Friendly string of the default value, for documentation. If doesn't create a default, throws
* and UnsupportedOperationException
*/
public String typeDefaultDocString(ArgumentSource source) {
throw new UnsupportedOperationException();
}
/**
* Generates a default for the given type.
*
* @param parsingEngine the parsing engine used to validate this argument type descriptor.
* @param source Source of the command-line argument.
* @param type Type of value to create, in case the command-line argument system wants influence.
* @return A default value for the given type.
*/
public Object createTypeDefault(ParsingEngine parsingEngine,ArgumentSource source, Type type) { throw new UnsupportedOperationException("Unable to create default for type " + getClass()); }
/**
* Given the given argument source and attributes, synthesize argument definitions for command-line arguments.
* @param source Source class and field for the given argument.
* @return A list of command-line argument definitions supporting this field.
*/
public List<ArgumentDefinition> createArgumentDefinitions( ArgumentSource source ) {
return Collections.singletonList(createDefaultArgumentDefinition(source));
}
/**
* Parses an argument source to an object.
* WARNING! Mandatory side effect of parsing! Each parse routine should register the tags it finds with the proper CommandLineProgram.
* TODO: Fix this, perhaps with an event model indicating that a new argument has been created.
*
* @param parsingEngine The engine responsible for parsing.
* @param source The source used to find the matches.
* @param matches The matches for the source.
* @return The parsed object.
*/
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, ArgumentMatches matches) {
return parse(parsingEngine, source, source.field.getGenericType(), matches);
}
/**
* Returns true if the field is a collection or an array.
* @param source The argument source to check.
* @return true if the field is a collection or an array.
*/
public boolean isMultiValued( ArgumentSource source ) {
Class argumentType = source.field.getType();
return Collection.class.isAssignableFrom(argumentType) || argumentType.isArray();
}
/**
* By default, argument sources create argument definitions with a set of default values.
* Use this method to create the one simple argument definition.
* @param source argument source for which to create a default definition.
* @return The default definition for this argument source.
*/
protected ArgumentDefinition createDefaultArgumentDefinition( ArgumentSource source ) {
Annotation argumentAnnotation = getArgumentAnnotation(source);
return new ArgumentDefinition( ArgumentIOType.getIOType(argumentAnnotation),
source.field.getType(),
ArgumentDefinition.getFullName(argumentAnnotation, source.field.getName()),
ArgumentDefinition.getShortName(argumentAnnotation),
ArgumentDefinition.getDoc(argumentAnnotation),
source.isRequired() && !createsTypeDefault(source) && !source.isFlag() && !source.isDeprecated(),
source.isFlag(),
source.isMultiValued(),
source.isHidden(),
makeRawTypeIfNecessary(getCollectionComponentType(source.field)),
ArgumentDefinition.getExclusiveOf(argumentAnnotation),
ArgumentDefinition.getValidationRegex(argumentAnnotation),
getValidOptions(source) );
}
/**
* Return the component type of a field, or String.class if the type cannot be found.
* @param field The reflected field to inspect.
* @return The parameterized component type, or String.class if the parameterized type could not be found.
* @throws IllegalArgumentException If more than one parameterized type is found on the field.
*/
protected Type getCollectionComponentType( Field field ) {
return null;
}
/**
* Parses the argument matches for a class type into an object.
* @param source The original argument source used to find the matches.
* @param type The current class type being inspected. May not match the argument source.field.getType() if this as a collection for example.
* @param matches The argument matches for the argument source, or the individual argument match for a scalar if this is being called to help parse a collection.
* @return The individual parsed object matching the argument match with Class type.
*/
public abstract Object parse( ParsingEngine parsingEngine, ArgumentSource source, Type type, ArgumentMatches matches );
/**
* If the argument source only accepts a small set of options, populate the returned list with
* those options. Otherwise, leave the list empty.
* @param source Original field specifying command-line arguments.
* @return A list of valid options.
*/
protected List<String> getValidOptions( ArgumentSource source ) {
if(!source.field.getType().isEnum())
return null;
List<String> validOptions = new ArrayList<String>();
for(Object constant: source.field.getType().getEnumConstants())
validOptions.add(constant.toString());
return validOptions;
}
/**
* Returns true if the argument with the given full name exists in the collection of ArgumentMatches.
* @param definition Definition of the argument for which to find matches.
* @param matches The matches for the given argument.
* @return true if the argument is present, or false if not present.
*/
protected boolean argumentIsPresent( ArgumentDefinition definition, ArgumentMatches matches ) {
for( ArgumentMatch match: matches ) {
if( match.definition.equals(definition) )
return true;
}
return false;
}
/**
* Gets the value of an argument with the given full name, from the collection of ArgumentMatches.
* If the argument matches multiple values, an exception will be thrown.
* @param definition Definition of the argument for which to find matches.
* @param matches The matches for the given argument.
* @return The value of the argument if available, or null if not present.
*/
protected String getArgumentValue( ArgumentDefinition definition, ArgumentMatches matches ) {
Collection<String> argumentValues = getArgumentValues( definition, matches );
if( argumentValues.size() > 1 )
throw new UserException.CommandLineException("Multiple values associated with given definition, but this argument expects only one: " + definition.fullName);
return argumentValues.size() > 0 ? argumentValues.iterator().next() : null;
}
/**
* Gets the tags associated with a given command-line argument.
* If the argument matches multiple values, an exception will be thrown.
* @param matches The matches for the given argument.
* @return The value of the argument if available, or null if not present.
*/
protected Tags getArgumentTags(ArgumentMatches matches) {
Tags tags = new Tags();
for(ArgumentMatch match: matches) {
if(!tags.isEmpty() && !match.tags.isEmpty())
throw new ReviewedStingException("BUG: multiple conflicting sets of tags are available, and the type descriptor specifies no way of resolving the conflict.");
tags = match.tags;
}
return tags;
}
/**
* Gets the values of an argument with the given full name, from the collection of ArgumentMatches.
* @param definition Definition of the argument for which to find matches.
* @param matches The matches for the given argument.
* @return The value of the argument if available, or an empty collection if not present.
*/
protected Collection<String> getArgumentValues( ArgumentDefinition definition, ArgumentMatches matches ) {
Collection<String> values = new ArrayList<String>();
for( ArgumentMatch match: matches ) {
if( match.definition.equals(definition) )
values.addAll(match.values());
}
return values;
}
/**
* Retrieves the argument description from the given argument source. Will throw an exception if
* the given ArgumentSource
* @param source source of the argument.
* @return Argument description annotation associated with the given field.
*/
@SuppressWarnings("unchecked")
protected static Annotation getArgumentAnnotation( ArgumentSource source ) {
for (Class annotation: ARGUMENT_ANNOTATIONS)
if (source.field.isAnnotationPresent(annotation))
return source.field.getAnnotation(annotation);
throw new ReviewedStingException("ArgumentAnnotation is not present for the argument field: " + source.field.getName());
}
/**
* Returns true if an argument annotation is present
* @param field The field to check for an annotation.
* @return True if an argument annotation is present on the field.
*/
@SuppressWarnings("unchecked")
public static boolean isArgumentAnnotationPresent(Field field) {
for (Class annotation: ARGUMENT_ANNOTATIONS)
if (field.isAnnotationPresent(annotation))
return true;
return false;
}
/**
* Returns true if the given annotation is hidden from the help system.
* @param field Field to test.
* @return True if argument should be hidden. False otherwise.
*/
public static boolean isArgumentHidden(Field field) {
return field.isAnnotationPresent(Hidden.class);
}
public Class makeRawTypeIfNecessary(Type t) {
if ( t == null )
return null;
else if ( t instanceof ParameterizedType )
return (Class)((ParameterizedType) t).getRawType();
else if ( t instanceof Class ) {
return (Class)t;
} else {
throw new IllegalArgumentException("Unable to determine Class-derived component type of field: " + t);
}
}
}
/**
* Parser for RodBinding objects
*/
class RodBindingArgumentTypeDescriptor extends ArgumentTypeDescriptor {
/**
* We only want RodBinding class objects
* @param type The type to check.
* @return true if the provided class is a RodBinding.class
*/
@Override
public boolean supports( Class type ) {
return isRodBinding(type);
}
public static boolean isRodBinding( Class type ) {
return RodBinding.class.isAssignableFrom(type);
}
@Override
public boolean createsTypeDefault(ArgumentSource source) { return ! source.isRequired(); }
@Override
public Object createTypeDefault(ParsingEngine parsingEngine, ArgumentSource source, Type type) {
Class parameterType = JVMUtils.getParameterizedTypeClass(type);
return RodBinding.makeUnbound((Class<? extends Feature>)parameterType);
}
@Override
public String typeDefaultDocString(ArgumentSource source) {
return "none";
}
@Override
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type type, ArgumentMatches matches) {
ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source);
String value = getArgumentValue( defaultDefinition, matches );
Class<? extends Feature> parameterType = JVMUtils.getParameterizedTypeClass(type);
try {
String name = defaultDefinition.fullName;
String tribbleType = null;
Tags tags = getArgumentTags(matches);
// must have one or two tag values here
if ( tags.getPositionalTags().size() > 2 ) {
throw new UserException.CommandLineException(
String.format("Unexpected number of positional tags for argument %s : %s. " +
"Rod bindings only suport -X:type and -X:name,type argument styles",
value, source.field.getName()));
} if ( tags.getPositionalTags().size() == 2 ) {
// -X:name,type style
name = tags.getPositionalTags().get(0);
tribbleType = tags.getPositionalTags().get(1);
} else {
// case with 0 or 1 positional tags
FeatureManager manager = new FeatureManager();
// -X:type style is a type when we cannot determine the type dynamically
String tag1 = tags.getPositionalTags().size() == 1 ? tags.getPositionalTags().get(0) : null;
if ( tag1 != null ) {
if ( manager.getByName(tag1) != null ) // this a type
tribbleType = tag1;
else
name = tag1;
}
if ( tribbleType == null ) {
// try to determine the file type dynamically
File file = new File(value);
if ( file.canRead() && file.isFile() ) {
FeatureManager.FeatureDescriptor featureDescriptor = manager.getByFiletype(file);
if ( featureDescriptor != null ) {
tribbleType = featureDescriptor.getName();
logger.info("Dynamically determined type of " + file + " to be " + tribbleType);
}
}
if ( tribbleType == null )
if ( ! file.exists() ) {
throw new UserException.CouldNotReadInputFile(file, "file does not exist");
- } else if ( ! file.canRead() | ! file.isFile() ) {
+ } else if ( ! file.canRead() || ! file.isFile() ) {
throw new UserException.CouldNotReadInputFile(file, "file could not be read");
} else {
throw new UserException.CommandLineException(
String.format("No tribble type was provided on the command line and the type of the file could not be determined dynamically. " +
"Please add an explicit type tag :NAME listing the correct type from among the supported types:%n%s",
manager.userFriendlyListOfAvailableFeatures(parameterType)));
}
}
}
Constructor ctor = (makeRawTypeIfNecessary(type)).getConstructor(Class.class, String.class, String.class, String.class, Tags.class);
RodBinding result = (RodBinding)ctor.newInstance(parameterType, name, value, tribbleType, tags);
parsingEngine.addTags(result,tags);
parsingEngine.addRodBinding(result);
return result;
} catch (InvocationTargetException e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s.",
value, source.field.getName()));
} catch (Exception e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s. Message: %s",
value, source.field.getName(), e.getMessage()));
}
}
}
/**
* Parse simple argument types: java primitives, wrapper classes, and anything that has
* a simple String constructor.
*/
class SimpleArgumentTypeDescriptor extends ArgumentTypeDescriptor {
@Override
public boolean supports( Class type ) {
if ( RodBindingArgumentTypeDescriptor.isRodBinding(type) ) return false;
if ( type.isPrimitive() ) return true;
if ( type.isEnum() ) return true;
if ( primitiveToWrapperMap.containsValue(type) ) return true;
try {
type.getConstructor(String.class);
return true;
}
catch( Exception ex ) {
// An exception thrown above means that the String constructor either doesn't
// exist or can't be accessed. In either case, this descriptor doesn't support this type.
return false;
}
}
@Override
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype, ArgumentMatches matches) {
Class type = makeRawTypeIfNecessary(fulltype);
if (source.isFlag())
return true;
ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source);
String value = getArgumentValue( defaultDefinition, matches );
Object result;
Tags tags = getArgumentTags(matches);
// lets go through the types we support
try {
if (type.isPrimitive()) {
Method valueOf = primitiveToWrapperMap.get(type).getMethod("valueOf",String.class);
if(value == null)
throw new MissingArgumentValueException(createDefaultArgumentDefinition(source));
result = valueOf.invoke(null,value.trim());
} else if (type.isEnum()) {
Object[] vals = type.getEnumConstants();
Object defaultEnumeration = null; // as we look at options, record the default option if it exists
for (Object val : vals) {
if (String.valueOf(val).equalsIgnoreCase(value)) return val;
try { if (type.getField(val.toString()).isAnnotationPresent(EnumerationArgumentDefault.class)) defaultEnumeration = val; }
catch (NoSuchFieldException e) { throw new ReviewedStingException("parsing " + type.toString() + "doesn't contain the field " + val.toString()); }
}
// if their argument has no value (null), and there's a default, return that default for the enum value
if (defaultEnumeration != null && value == null)
result = defaultEnumeration;
// if their argument has no value and there's no default, throw a missing argument value exception.
// TODO: Clean this up so that null values never make it to this point. To fix this, we'll have to clean up the implementation of -U.
else if (value == null)
throw new MissingArgumentValueException(createDefaultArgumentDefinition(source));
else
throw new UnknownEnumeratedValueException(createDefaultArgumentDefinition(source),value);
} else {
Constructor ctor = type.getConstructor(String.class);
result = ctor.newInstance(value);
}
} catch (UserException e) {
throw e;
} catch (InvocationTargetException e) {
throw new UserException.CommandLineException(String.format("Failed to parse value %s for argument %s. This is most commonly caused by providing an incorrect data type (e.g. a double when an int is required)",
value, source.field.getName()));
} catch (Exception e) {
throw new DynamicClassResolutionException(String.class, e);
}
// TODO FIXME!
// WARNING: Side effect!
parsingEngine.addTags(result,tags);
return result;
}
/**
* A mapping of the primitive types to their associated wrapper classes. Is there really no way to infer
* this association available in the JRE?
*/
private static Map<Class,Class> primitiveToWrapperMap = new HashMap<Class,Class>() {
{
put( Boolean.TYPE, Boolean.class );
put( Character.TYPE, Character.class );
put( Byte.TYPE, Byte.class );
put( Short.TYPE, Short.class );
put( Integer.TYPE, Integer.class );
put( Long.TYPE, Long.class );
put( Float.TYPE, Float.class );
put( Double.TYPE, Double.class );
}
};
}
/**
* Process compound argument types: arrays, and typed and untyped collections.
*/
class CompoundArgumentTypeDescriptor extends ArgumentTypeDescriptor {
@Override
public boolean supports( Class type ) {
return ( Collection.class.isAssignableFrom(type) || type.isArray() );
}
@Override
@SuppressWarnings("unchecked")
public Object parse(ParsingEngine parsingEngine,ArgumentSource source, Type fulltype, ArgumentMatches matches) {
Class type = makeRawTypeIfNecessary(fulltype);
Type componentType;
Object result;
if( Collection.class.isAssignableFrom(type) ) {
// If this is a generic interface, pick a concrete implementation to create and pass back.
// Because of type erasure, don't worry about creating one of exactly the correct type.
if( Modifier.isInterface(type.getModifiers()) || Modifier.isAbstract(type.getModifiers()) )
{
if( java.util.List.class.isAssignableFrom(type) ) type = ArrayList.class;
else if( java.util.Queue.class.isAssignableFrom(type) ) type = java.util.ArrayDeque.class;
else if( java.util.Set.class.isAssignableFrom(type) ) type = java.util.TreeSet.class;
}
componentType = getCollectionComponentType( source.field );
ArgumentTypeDescriptor componentArgumentParser = parsingEngine.selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));
Collection collection;
try {
collection = (Collection)type.newInstance();
}
catch (InstantiationException e) {
logger.fatal("ArgumentParser: InstantiationException: cannot convert field " + source.field.getName());
throw new ReviewedStingException("constructFromString:InstantiationException: Failed conversion " + e.getMessage());
}
catch (IllegalAccessException e) {
logger.fatal("ArgumentParser: IllegalAccessException: cannot convert field " + source.field.getName());
throw new ReviewedStingException("constructFromString:IllegalAccessException: Failed conversion " + e.getMessage());
}
for( ArgumentMatch match: matches ) {
for( ArgumentMatch value: match ) {
Object object = componentArgumentParser.parse(parsingEngine,source,componentType,new ArgumentMatches(value));
collection.add( object );
// WARNING: Side effect!
parsingEngine.addTags(object,value.tags);
}
}
result = collection;
}
else if( type.isArray() ) {
componentType = type.getComponentType();
ArgumentTypeDescriptor componentArgumentParser = parsingEngine.selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));
// Assemble a collection of individual values used in this computation.
Collection<ArgumentMatch> values = new ArrayList<ArgumentMatch>();
for( ArgumentMatch match: matches )
for( ArgumentMatch value: match )
values.add(value);
result = Array.newInstance(makeRawTypeIfNecessary(componentType),values.size());
int i = 0;
for( ArgumentMatch value: values ) {
Object object = componentArgumentParser.parse(parsingEngine,source,componentType,new ArgumentMatches(value));
Array.set(result,i++,object);
// WARNING: Side effect!
parsingEngine.addTags(object,value.tags);
}
}
else
throw new ReviewedStingException("Unsupported compound argument type: " + type);
return result;
}
/**
* Return the component type of a field, or String.class if the type cannot be found.
* @param field The reflected field to inspect.
* @return The parameterized component type, or String.class if the parameterized type could not be found.
* @throws IllegalArgumentException If more than one parameterized type is found on the field.
*/
@Override
protected Type getCollectionComponentType( Field field ) {
// If this is a parameterized collection, find the contained type. If blow up if more than one type exists.
if( field.getGenericType() instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)field.getGenericType();
if( parameterizedType.getActualTypeArguments().length > 1 )
throw new IllegalArgumentException("Unable to determine collection type of field: " + field.toString());
return parameterizedType.getActualTypeArguments()[0];
}
else
return String.class;
}
}
class MultiplexArgumentTypeDescriptor extends ArgumentTypeDescriptor {
/**
* The multiplexer controlling how data is split.
*/
private final Multiplexer multiplexer;
/**
* The set of identifiers for the multiplexed entries.
*/
private final Collection<?> multiplexedIds;
public MultiplexArgumentTypeDescriptor() {
this.multiplexer = null;
this.multiplexedIds = null;
}
/**
* Private constructor to use in creating a closure of the MultiplexArgumentTypeDescriptor specific to the
* given set of multiplexed ids.
* @param multiplexedIds The collection of multiplexed entries
*/
private MultiplexArgumentTypeDescriptor(final Multiplexer multiplexer, final Collection<?> multiplexedIds) {
this.multiplexer = multiplexer;
this.multiplexedIds = multiplexedIds;
}
@Override
public boolean supports( Class type ) {
return ( Map.class.isAssignableFrom(type) );
}
@Override
public boolean createsTypeDefault(ArgumentSource source) {
// Multiplexing always creates a type default.
return true;
}
@Override
public Object createTypeDefault(ParsingEngine parsingEngine,ArgumentSource source, Type type) {
if(multiplexer == null || multiplexedIds == null)
throw new ReviewedStingException("No multiplexed ids available");
Map<Object,Object> multiplexedMapping = new HashMap<Object,Object>();
Class componentType = makeRawTypeIfNecessary(getCollectionComponentType(source.field));
ArgumentTypeDescriptor componentTypeDescriptor = parsingEngine.selectBestTypeDescriptor(componentType);
for(Object id: multiplexedIds) {
Object value = null;
if(componentTypeDescriptor.createsTypeDefault(source))
value = componentTypeDescriptor.createTypeDefault(parsingEngine,source,componentType);
multiplexedMapping.put(id,value);
}
return multiplexedMapping;
}
@Override
public String typeDefaultDocString(ArgumentSource source) {
return "None";
}
@Override
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type type, ArgumentMatches matches) {
if(multiplexedIds == null)
throw new ReviewedStingException("Cannot directly parse a MultiplexArgumentTypeDescriptor; must create a derivative type descriptor first.");
Map<Object,Object> multiplexedMapping = new HashMap<Object,Object>();
Class componentType = makeRawTypeIfNecessary(getCollectionComponentType(source.field));
for(Object id: multiplexedIds) {
Object value = parsingEngine.selectBestTypeDescriptor(componentType).parse(parsingEngine,source,componentType,matches.transform(multiplexer,id));
multiplexedMapping.put(id,value);
}
parsingEngine.addTags(multiplexedMapping,getArgumentTags(matches));
return multiplexedMapping;
}
public MultiplexArgumentTypeDescriptor createCustomTypeDescriptor(ParsingEngine parsingEngine,ArgumentSource dependentArgument,Object containingObject) {
String[] sourceFields = dependentArgument.field.getAnnotation(Multiplex.class).arguments();
List<ArgumentSource> allSources = parsingEngine.extractArgumentSources(containingObject.getClass());
Class[] sourceTypes = new Class[sourceFields.length];
Object[] sourceValues = new Object[sourceFields.length];
int currentField = 0;
for(String sourceField: sourceFields) {
boolean fieldFound = false;
for(ArgumentSource source: allSources) {
if(!source.field.getName().equals(sourceField))
continue;
if(source.field.isAnnotationPresent(Multiplex.class))
throw new ReviewedStingException("Command-line arguments can only depend on independent fields");
sourceTypes[currentField] = source.field.getType();
sourceValues[currentField] = JVMUtils.getFieldValue(source.field,containingObject);
currentField++;
fieldFound = true;
}
if(!fieldFound)
throw new ReviewedStingException(String.format("Unable to find source field %s, referred to by dependent field %s",sourceField,dependentArgument.field.getName()));
}
Class<? extends Multiplexer> multiplexerType = dependentArgument.field.getAnnotation(Multiplex.class).value();
Constructor<? extends Multiplexer> multiplexerConstructor = null;
try {
multiplexerConstructor = multiplexerType.getConstructor(sourceTypes);
multiplexerConstructor.setAccessible(true);
}
catch(NoSuchMethodException ex) {
throw new ReviewedStingException(String.format("Unable to find constructor for class %s with parameters %s",multiplexerType.getName(),Arrays.deepToString(sourceFields)),ex);
}
Multiplexer multiplexer = null;
try {
multiplexer = multiplexerConstructor.newInstance(sourceValues);
}
catch(IllegalAccessException ex) {
throw new ReviewedStingException(String.format("Constructor for class %s with parameters %s is inaccessible",multiplexerType.getName(),Arrays.deepToString(sourceFields)),ex);
}
catch(InstantiationException ex) {
throw new ReviewedStingException(String.format("Can't create class %s with parameters %s",multiplexerType.getName(),Arrays.deepToString(sourceFields)),ex);
}
catch(InvocationTargetException ex) {
throw new ReviewedStingException(String.format("Can't invoke constructor of class %s with parameters %s",multiplexerType.getName(),Arrays.deepToString(sourceFields)),ex);
}
return new MultiplexArgumentTypeDescriptor(multiplexer,multiplexer.multiplex());
}
/**
* Return the component type of a field, or String.class if the type cannot be found.
* @param field The reflected field to inspect.
* @return The parameterized component type, or String.class if the parameterized type could not be found.
* @throws IllegalArgumentException If more than one parameterized type is found on the field.
*/
@Override
protected Type getCollectionComponentType( Field field ) {
// Multiplex arguments must resolve to maps from which the clp should extract the second type.
if( field.getGenericType() instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)field.getGenericType();
if( parameterizedType.getActualTypeArguments().length != 2 )
throw new IllegalArgumentException("Unable to determine collection type of field: " + field.toString());
return (Class)parameterizedType.getActualTypeArguments()[1];
}
else
return String.class;
}
}
| true | true |
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type type, ArgumentMatches matches) {
ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source);
String value = getArgumentValue( defaultDefinition, matches );
Class<? extends Feature> parameterType = JVMUtils.getParameterizedTypeClass(type);
try {
String name = defaultDefinition.fullName;
String tribbleType = null;
Tags tags = getArgumentTags(matches);
// must have one or two tag values here
if ( tags.getPositionalTags().size() > 2 ) {
throw new UserException.CommandLineException(
String.format("Unexpected number of positional tags for argument %s : %s. " +
"Rod bindings only suport -X:type and -X:name,type argument styles",
value, source.field.getName()));
} if ( tags.getPositionalTags().size() == 2 ) {
// -X:name,type style
name = tags.getPositionalTags().get(0);
tribbleType = tags.getPositionalTags().get(1);
} else {
// case with 0 or 1 positional tags
FeatureManager manager = new FeatureManager();
// -X:type style is a type when we cannot determine the type dynamically
String tag1 = tags.getPositionalTags().size() == 1 ? tags.getPositionalTags().get(0) : null;
if ( tag1 != null ) {
if ( manager.getByName(tag1) != null ) // this a type
tribbleType = tag1;
else
name = tag1;
}
if ( tribbleType == null ) {
// try to determine the file type dynamically
File file = new File(value);
if ( file.canRead() && file.isFile() ) {
FeatureManager.FeatureDescriptor featureDescriptor = manager.getByFiletype(file);
if ( featureDescriptor != null ) {
tribbleType = featureDescriptor.getName();
logger.info("Dynamically determined type of " + file + " to be " + tribbleType);
}
}
if ( tribbleType == null )
if ( ! file.exists() ) {
throw new UserException.CouldNotReadInputFile(file, "file does not exist");
} else if ( ! file.canRead() | ! file.isFile() ) {
throw new UserException.CouldNotReadInputFile(file, "file could not be read");
} else {
throw new UserException.CommandLineException(
String.format("No tribble type was provided on the command line and the type of the file could not be determined dynamically. " +
"Please add an explicit type tag :NAME listing the correct type from among the supported types:%n%s",
manager.userFriendlyListOfAvailableFeatures(parameterType)));
}
}
}
Constructor ctor = (makeRawTypeIfNecessary(type)).getConstructor(Class.class, String.class, String.class, String.class, Tags.class);
RodBinding result = (RodBinding)ctor.newInstance(parameterType, name, value, tribbleType, tags);
parsingEngine.addTags(result,tags);
parsingEngine.addRodBinding(result);
return result;
} catch (InvocationTargetException e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s.",
value, source.field.getName()));
} catch (Exception e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s. Message: %s",
value, source.field.getName(), e.getMessage()));
}
}
|
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type type, ArgumentMatches matches) {
ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source);
String value = getArgumentValue( defaultDefinition, matches );
Class<? extends Feature> parameterType = JVMUtils.getParameterizedTypeClass(type);
try {
String name = defaultDefinition.fullName;
String tribbleType = null;
Tags tags = getArgumentTags(matches);
// must have one or two tag values here
if ( tags.getPositionalTags().size() > 2 ) {
throw new UserException.CommandLineException(
String.format("Unexpected number of positional tags for argument %s : %s. " +
"Rod bindings only suport -X:type and -X:name,type argument styles",
value, source.field.getName()));
} if ( tags.getPositionalTags().size() == 2 ) {
// -X:name,type style
name = tags.getPositionalTags().get(0);
tribbleType = tags.getPositionalTags().get(1);
} else {
// case with 0 or 1 positional tags
FeatureManager manager = new FeatureManager();
// -X:type style is a type when we cannot determine the type dynamically
String tag1 = tags.getPositionalTags().size() == 1 ? tags.getPositionalTags().get(0) : null;
if ( tag1 != null ) {
if ( manager.getByName(tag1) != null ) // this a type
tribbleType = tag1;
else
name = tag1;
}
if ( tribbleType == null ) {
// try to determine the file type dynamically
File file = new File(value);
if ( file.canRead() && file.isFile() ) {
FeatureManager.FeatureDescriptor featureDescriptor = manager.getByFiletype(file);
if ( featureDescriptor != null ) {
tribbleType = featureDescriptor.getName();
logger.info("Dynamically determined type of " + file + " to be " + tribbleType);
}
}
if ( tribbleType == null )
if ( ! file.exists() ) {
throw new UserException.CouldNotReadInputFile(file, "file does not exist");
} else if ( ! file.canRead() || ! file.isFile() ) {
throw new UserException.CouldNotReadInputFile(file, "file could not be read");
} else {
throw new UserException.CommandLineException(
String.format("No tribble type was provided on the command line and the type of the file could not be determined dynamically. " +
"Please add an explicit type tag :NAME listing the correct type from among the supported types:%n%s",
manager.userFriendlyListOfAvailableFeatures(parameterType)));
}
}
}
Constructor ctor = (makeRawTypeIfNecessary(type)).getConstructor(Class.class, String.class, String.class, String.class, Tags.class);
RodBinding result = (RodBinding)ctor.newInstance(parameterType, name, value, tribbleType, tags);
parsingEngine.addTags(result,tags);
parsingEngine.addRodBinding(result);
return result;
} catch (InvocationTargetException e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s.",
value, source.field.getName()));
} catch (Exception e) {
throw new UserException.CommandLineException(
String.format("Failed to parse value %s for argument %s. Message: %s",
value, source.field.getName(), e.getMessage()));
}
}
|
diff --git a/src/main/java/org/spout/api/model/mesh/CubeMesh.java b/src/main/java/org/spout/api/model/mesh/CubeMesh.java
index bfae56b15..71296164e 100644
--- a/src/main/java/org/spout/api/model/mesh/CubeMesh.java
+++ b/src/main/java/org/spout/api/model/mesh/CubeMesh.java
@@ -1,111 +1,111 @@
/*
* This file is part of SpoutAPI.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* SpoutAPI is licensed under the SpoutDev License Version 1.
*
* SpoutAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* SpoutAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.api.model.mesh;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import org.spout.api.material.block.BlockFace;
import org.spout.api.math.Vector2;
import org.spout.api.math.Vector3;
public class CubeMesh extends OrientedMesh {
public CubeMesh(Vector2 [][] uvs){
super(new ArrayList<OrientedMeshFace>(12));
Vector3 vertex0 = new Vector3(0, 0, 0);
Vector3 vertex1 = new Vector3(0, 1, 0);
Vector3 vertex2 = new Vector3(1, 1, 0);
Vector3 vertex3 = new Vector3(1, 0, 0);
Vector3 vertex4 = new Vector3(0, 0, 1);
Vector3 vertex5 = new Vector3(0, 1, 1);
Vector3 vertex6 = new Vector3(1, 1, 1);
Vector3 vertex7 = new Vector3(1, 0, 1);
Vertex v1 = null, v2 = null, v3 = null, v4 = null;
/* 1--2
* /| /|
* 5--6 |
* | 0|-3 Y - Bottom < TOP
* |/ |/ |
* 4--7 O-- X - North < SOUTH
* /
* Z - East < WEST
*/
v1 = new Vertex(vertex1, BlockFace.TOP.getOffset(), getUV(uvs, 0, 3));
v2 = new Vertex(vertex2, BlockFace.TOP.getOffset(), getUV(uvs, 0, 2));
v3 = new Vertex(vertex6, BlockFace.TOP.getOffset(), getUV(uvs, 0, 1));
v4 = new Vertex(vertex5, BlockFace.TOP.getOffset(), getUV(uvs, 0, 0));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
- v1 = new Vertex(vertex0, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 3));
- v2 = new Vertex(vertex4, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 2));
- v3 = new Vertex(vertex7, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 1));
- v4 = new Vertex(vertex3, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 0));
+ v1 = new Vertex(vertex0, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 0));
+ v2 = new Vertex(vertex4, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 3));
+ v3 = new Vertex(vertex7, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 2));
+ v4 = new Vertex(vertex3, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 1));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
- v1 = new Vertex(vertex0, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 2));
- v2 = new Vertex(vertex1, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 1));
- v3 = new Vertex(vertex5, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 0));
- v4 = new Vertex(vertex4, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 3));
+ v1 = new Vertex(vertex0, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 1));
+ v2 = new Vertex(vertex1, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 0));
+ v3 = new Vertex(vertex5, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 3));
+ v4 = new Vertex(vertex4, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 2));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
v1 = new Vertex(vertex7, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 1));
v2 = new Vertex(vertex6, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 0));
v3 = new Vertex(vertex2, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 3));
v4 = new Vertex(vertex3, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 2));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
v1 = new Vertex(vertex0, BlockFace.EAST.getOffset(), getUV(uvs, 4, 2));
v2 = new Vertex(vertex3, BlockFace.EAST.getOffset(), getUV(uvs, 4, 1));
v3 = new Vertex(vertex2, BlockFace.EAST.getOffset(), getUV(uvs, 4, 0));
v4 = new Vertex(vertex1, BlockFace.EAST.getOffset(), getUV(uvs, 4, 3));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
v1 = new Vertex(vertex5, BlockFace.WEST.getOffset(), getUV(uvs, 5, 0));
v2 = new Vertex(vertex6, BlockFace.WEST.getOffset(), getUV(uvs, 5, 3));
v3 = new Vertex(vertex7, BlockFace.WEST.getOffset(), getUV(uvs, 5, 2));
v4 = new Vertex(vertex4, BlockFace.WEST.getOffset(), getUV(uvs, 5, 1));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
}
private static Vector2 getUV(Vector2 [][] uvs, int face, int vertex) {
int i = face % uvs.length; //Allow to render all face of a cube with a one face specified
return uvs[i][vertex % uvs[i].length];
}
}
| false | true |
public CubeMesh(Vector2 [][] uvs){
super(new ArrayList<OrientedMeshFace>(12));
Vector3 vertex0 = new Vector3(0, 0, 0);
Vector3 vertex1 = new Vector3(0, 1, 0);
Vector3 vertex2 = new Vector3(1, 1, 0);
Vector3 vertex3 = new Vector3(1, 0, 0);
Vector3 vertex4 = new Vector3(0, 0, 1);
Vector3 vertex5 = new Vector3(0, 1, 1);
Vector3 vertex6 = new Vector3(1, 1, 1);
Vector3 vertex7 = new Vector3(1, 0, 1);
Vertex v1 = null, v2 = null, v3 = null, v4 = null;
/* 1--2
* /| /|
* 5--6 |
* | 0|-3 Y - Bottom < TOP
* |/ |/ |
* 4--7 O-- X - North < SOUTH
* /
* Z - East < WEST
*/
v1 = new Vertex(vertex1, BlockFace.TOP.getOffset(), getUV(uvs, 0, 3));
v2 = new Vertex(vertex2, BlockFace.TOP.getOffset(), getUV(uvs, 0, 2));
v3 = new Vertex(vertex6, BlockFace.TOP.getOffset(), getUV(uvs, 0, 1));
v4 = new Vertex(vertex5, BlockFace.TOP.getOffset(), getUV(uvs, 0, 0));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
v1 = new Vertex(vertex0, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 3));
v2 = new Vertex(vertex4, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 2));
v3 = new Vertex(vertex7, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 1));
v4 = new Vertex(vertex3, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 0));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
v1 = new Vertex(vertex0, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 2));
v2 = new Vertex(vertex1, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 1));
v3 = new Vertex(vertex5, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 0));
v4 = new Vertex(vertex4, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 3));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
v1 = new Vertex(vertex7, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 1));
v2 = new Vertex(vertex6, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 0));
v3 = new Vertex(vertex2, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 3));
v4 = new Vertex(vertex3, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 2));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
v1 = new Vertex(vertex0, BlockFace.EAST.getOffset(), getUV(uvs, 4, 2));
v2 = new Vertex(vertex3, BlockFace.EAST.getOffset(), getUV(uvs, 4, 1));
v3 = new Vertex(vertex2, BlockFace.EAST.getOffset(), getUV(uvs, 4, 0));
v4 = new Vertex(vertex1, BlockFace.EAST.getOffset(), getUV(uvs, 4, 3));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
v1 = new Vertex(vertex5, BlockFace.WEST.getOffset(), getUV(uvs, 5, 0));
v2 = new Vertex(vertex6, BlockFace.WEST.getOffset(), getUV(uvs, 5, 3));
v3 = new Vertex(vertex7, BlockFace.WEST.getOffset(), getUV(uvs, 5, 2));
v4 = new Vertex(vertex4, BlockFace.WEST.getOffset(), getUV(uvs, 5, 1));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
}
|
public CubeMesh(Vector2 [][] uvs){
super(new ArrayList<OrientedMeshFace>(12));
Vector3 vertex0 = new Vector3(0, 0, 0);
Vector3 vertex1 = new Vector3(0, 1, 0);
Vector3 vertex2 = new Vector3(1, 1, 0);
Vector3 vertex3 = new Vector3(1, 0, 0);
Vector3 vertex4 = new Vector3(0, 0, 1);
Vector3 vertex5 = new Vector3(0, 1, 1);
Vector3 vertex6 = new Vector3(1, 1, 1);
Vector3 vertex7 = new Vector3(1, 0, 1);
Vertex v1 = null, v2 = null, v3 = null, v4 = null;
/* 1--2
* /| /|
* 5--6 |
* | 0|-3 Y - Bottom < TOP
* |/ |/ |
* 4--7 O-- X - North < SOUTH
* /
* Z - East < WEST
*/
v1 = new Vertex(vertex1, BlockFace.TOP.getOffset(), getUV(uvs, 0, 3));
v2 = new Vertex(vertex2, BlockFace.TOP.getOffset(), getUV(uvs, 0, 2));
v3 = new Vertex(vertex6, BlockFace.TOP.getOffset(), getUV(uvs, 0, 1));
v4 = new Vertex(vertex5, BlockFace.TOP.getOffset(), getUV(uvs, 0, 0));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.TOP))));
v1 = new Vertex(vertex0, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 0));
v2 = new Vertex(vertex4, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 3));
v3 = new Vertex(vertex7, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 2));
v4 = new Vertex(vertex3, BlockFace.BOTTOM.getOffset(), getUV(uvs, 1, 1));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.BOTTOM))));
v1 = new Vertex(vertex0, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 1));
v2 = new Vertex(vertex1, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 0));
v3 = new Vertex(vertex5, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 3));
v4 = new Vertex(vertex4, BlockFace.NORTH.getOffset(), getUV(uvs, 2, 2));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.NORTH))));
v1 = new Vertex(vertex7, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 1));
v2 = new Vertex(vertex6, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 0));
v3 = new Vertex(vertex2, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 3));
v4 = new Vertex(vertex3, BlockFace.SOUTH.getOffset(), getUV(uvs, 3, 2));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.SOUTH))));
v1 = new Vertex(vertex0, BlockFace.EAST.getOffset(), getUV(uvs, 4, 2));
v2 = new Vertex(vertex3, BlockFace.EAST.getOffset(), getUV(uvs, 4, 1));
v3 = new Vertex(vertex2, BlockFace.EAST.getOffset(), getUV(uvs, 4, 0));
v4 = new Vertex(vertex1, BlockFace.EAST.getOffset(), getUV(uvs, 4, 3));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.EAST))));
v1 = new Vertex(vertex5, BlockFace.WEST.getOffset(), getUV(uvs, 5, 0));
v2 = new Vertex(vertex6, BlockFace.WEST.getOffset(), getUV(uvs, 5, 3));
v3 = new Vertex(vertex7, BlockFace.WEST.getOffset(), getUV(uvs, 5, 2));
v4 = new Vertex(vertex4, BlockFace.WEST.getOffset(), getUV(uvs, 5, 1));
meshFace.add(new OrientedMeshFace(v1, v2, v3, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
meshFace.add(new OrientedMeshFace(v3, v4, v1, new HashSet<BlockFace>(Arrays.asList(BlockFace.WEST))));
}
|
diff --git a/modules/jetty/src/main/java/org/mortbay/jetty/HttpParser.java b/modules/jetty/src/main/java/org/mortbay/jetty/HttpParser.java
index e155159..3430c48 100644
--- a/modules/jetty/src/main/java/org/mortbay/jetty/HttpParser.java
+++ b/modules/jetty/src/main/java/org/mortbay/jetty/HttpParser.java
@@ -1,1185 +1,1185 @@
// ========================================================================
// Copyright 2004-2006 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.jetty;
import java.io.IOException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.io.Buffer;
import org.mortbay.io.BufferUtil;
import org.mortbay.io.Buffers;
import org.mortbay.io.ByteArrayBuffer;
import org.mortbay.io.EndPoint;
import org.mortbay.io.View;
import org.mortbay.io.BufferCache.CachedBuffer;
import org.mortbay.log.Log;
/* ------------------------------------------------------------------------------- */
/**
* @author gregw
*/
public class HttpParser implements Parser
{
// States
public static final int STATE_START=-13;
public static final int STATE_FIELD0=-12;
public static final int STATE_SPACE1=-11;
public static final int STATE_FIELD1=-10;
public static final int STATE_SPACE2=-9;
public static final int STATE_END0=-8;
public static final int STATE_END1=-7;
public static final int STATE_FIELD2=-6;
public static final int STATE_HEADER=-5;
public static final int STATE_HEADER_NAME=-4;
public static final int STATE_HEADER_IN_NAME=-3;
public static final int STATE_HEADER_VALUE=-2;
public static final int STATE_HEADER_IN_VALUE=-1;
public static final int STATE_END=0;
public static final int STATE_EOF_CONTENT=1;
public static final int STATE_CONTENT=2;
public static final int STATE_CHUNKED_CONTENT=3;
public static final int STATE_CHUNK_SIZE=4;
public static final int STATE_CHUNK_PARAMS=5;
public static final int STATE_CHUNK=6;
private Buffers _buffers; // source of buffers
private EndPoint _endp;
private Buffer _header; // Buffer for header data (and small _content)
private Buffer _body; // Buffer for large content
private Buffer _buffer; // The current buffer in use (either _header or _content)
private View _contentView=new View(); // View of the content in the buffer for {@link Input}
private int _headerBufferSize;
private int _contentBufferSize;
private EventHandler _handler;
private CachedBuffer _cached;
private View.CaseInsensitive _tok0; // Saved token: header name, request method or response version
private View.CaseInsensitive _tok1; // Saved token: header value, request URI or response code
private String _multiLineValue;
private int _responseStatus; // If >0 then we are parsing a response
private boolean _forceContentBuffer;
private Input _input;
/* ------------------------------------------------------------------------------- */
protected int _state=STATE_START;
protected byte _eol;
protected int _length;
protected long _contentLength;
protected long _contentPosition;
protected int _chunkLength;
protected int _chunkPosition;
/* ------------------------------------------------------------------------------- */
/**
* Constructor.
*/
public HttpParser(Buffer buffer, EventHandler handler)
{
this._header=buffer;
this._buffer=buffer;
this._handler=handler;
if (buffer != null)
{
_tok0=new View.CaseInsensitive(buffer);
_tok1=new View.CaseInsensitive(buffer);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
}
}
/* ------------------------------------------------------------------------------- */
/**
* Constructor.
* @param headerBufferSize size in bytes of header buffer
* @param contentBufferSize size in bytes of content buffer
*/
public HttpParser(Buffers buffers, EndPoint endp, EventHandler handler, int headerBufferSize, int contentBufferSize)
{
_buffers=buffers;
_endp=endp;
_handler=handler;
_headerBufferSize=headerBufferSize;
_contentBufferSize=contentBufferSize;
}
/* ------------------------------------------------------------------------------- */
public long getContentLength()
{
return _contentLength;
}
public long getContentRead()
{
return _contentPosition;
}
/* ------------------------------------------------------------------------------- */
public int getState()
{
return _state;
}
/* ------------------------------------------------------------------------------- */
public boolean inContentState()
{
return _state > 0;
}
/* ------------------------------------------------------------------------------- */
public boolean inHeaderState()
{
return _state < 0;
}
/* ------------------------------------------------------------------------------- */
public boolean isChunking()
{
return _contentLength==HttpTokens.CHUNKED_CONTENT;
}
/* ------------------------------------------------------------ */
public boolean isIdle()
{
return isState(STATE_START);
}
/* ------------------------------------------------------------ */
public boolean isComplete()
{
return isState(STATE_END);
}
/* ------------------------------------------------------------ */
public boolean isMoreInBuffer()
throws IOException
{
if ( _header!=null && _header.hasContent() ||
_body!=null && _body.hasContent())
return true;
return false;
}
/* ------------------------------------------------------------------------------- */
public boolean isState(int state)
{
return _state == state;
}
/* ------------------------------------------------------------------------------- */
/**
* Parse until {@link #STATE_END END} state.
* If the parser is already in the END state, then it is {@link #reset reset} and re-parsed.
* @throws IllegalStateException If the buffers have already been partially parsed.
*/
public void parse() throws IOException
{
if (_state==STATE_END)
reset(false);
if (_state!=STATE_START)
throw new IllegalStateException("!START");
// continue parsing
while (_state != STATE_END)
parseNext();
}
/* ------------------------------------------------------------------------------- */
/**
* Parse until END state.
* This method will parse any remaining content in the current buffer. It does not care about the
* {@link #getState current state} of the parser.
* @see #parse
* @see #parseNext
*/
public long parseAvailable() throws IOException
{
long len = parseNext();
long total=len>0?len:0;
// continue parsing
while (!isComplete() && _buffer!=null && _buffer.length()>0)
{
len = parseNext();
if (len>0)
total+=len;
}
return total;
}
/* ------------------------------------------------------------------------------- */
/**
* Parse until next Event.
* @returns number of bytes filled from endpoint or -1 if fill never called.
*/
public long parseNext() throws IOException
{
long total_filled=-1;
if (_state == STATE_END)
return -1;
if (_buffer==null)
{
if (_header == null)
{
_header=_buffers.getBuffer(_headerBufferSize);
}
_buffer=_header;
_tok0=new View.CaseInsensitive(_header);
_tok1=new View.CaseInsensitive(_header);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
}
if (_state == STATE_CONTENT && _contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
int length=_buffer.length();
// Fill buffer if we can
if (length == 0)
{
int filled=-1;
if (_body!=null && _buffer!=_body)
{
_buffer=_body;
filled=_buffer.length();
}
if (_buffer.markIndex() == 0 && _buffer.putIndex() == _buffer.capacity())
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL");
IOException ioex=null;
if (_endp != null && filled<=0)
{
// Compress buffer if handling _content buffer
// TODO check this is not moving data too much
if (_buffer == _body)
_buffer.compact();
if (_buffer.space() == 0)
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL "+(_buffer==_body?"body":"head"));
try
{
if (total_filled<0)
total_filled=0;
filled=_endp.fill(_buffer);
if (filled>0)
total_filled+=filled;
}
catch(IOException e)
{
Log.debug(e);
ioex=e;
filled=-1;
}
}
if (filled < 0)
{
if ( _state == STATE_EOF_CONTENT)
{
if (_buffer.length()>0)
{
// TODO should we do this here or fall down to main loop?
Buffer chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
}
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
reset(true);
throw new EofException(ioex);
}
length=_buffer.length();
}
// EventHandler header
byte ch;
byte[] array=_buffer.array();
while (_state<STATE_END && length-->0)
{
ch=_buffer.get();
if (_eol == HttpTokens.CARRIAGE_RETURN && ch == HttpTokens.LINE_FEED)
{
_eol=HttpTokens.LINE_FEED;
continue;
}
_eol=0;
switch (_state)
{
case STATE_START:
_contentLength=HttpTokens.UNKNOWN_CONTENT;
_cached=null;
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD0;
}
break;
case STATE_FIELD0:
if (ch == HttpTokens.SPACE)
{
_tok0.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE1;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_SPACE1:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD1;
}
else if (ch < HttpTokens.SPACE)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_FIELD1:
if (ch == HttpTokens.SPACE)
{
_tok1.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE2;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _buffer
.sliceFromMark(), null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_SPACE2:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD2;
}
else if (ch < HttpTokens.SPACE)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _tok1, null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_FIELD2:
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// TODO - we really should know if we are parsing request or response!
final Buffer method = HttpMethods.CACHE.lookup(_tok0);
- if (method==_tok0 && _tok1.length()==3 && Character.isDigit(_tok1.peek()))
+ if (method==_tok0 && _tok1.length()==3 && Character.isDigit((char)_tok1.peek()))
{
_responseStatus = BufferUtil.toInt(_tok1);
_handler.startResponse(HttpVersions.CACHE.lookup(_tok0), _responseStatus,_buffer.sliceFromMark());
}
else
_handler.startRequest(method, _tok1,HttpVersions.CACHE.lookup(_buffer.sliceFromMark()));
_eol=ch;
_state=STATE_HEADER;
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
continue;
// return total_filled;
}
break;
case STATE_HEADER:
switch(ch)
{
case HttpTokens.COLON:
case HttpTokens.SPACE:
case HttpTokens.TAB:
{
// header value without name - continuation?
_length=-1;
_state=STATE_HEADER_VALUE;
break;
}
default:
{
// handler last header if any
if (_cached!=null || _tok0.length() > 0 || _tok1.length() > 0 || _multiLineValue != null)
{
Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0);
_cached=null;
Buffer value=_multiLineValue == null ? (Buffer) _tok1 : (Buffer) new ByteArrayBuffer(_multiLineValue);
int ho=HttpHeaders.CACHE.getOrdinal(header);
if (ho >= 0)
{
int vo=-1;
switch (ho)
{
case HttpHeaders.CONTENT_LENGTH_ORDINAL:
if (_contentLength != HttpTokens.CHUNKED_CONTENT)
{
_contentLength=BufferUtil.toLong(value);
if (_contentLength <= 0)
_contentLength=HttpTokens.NO_CONTENT;
}
break;
case HttpHeaders.TRANSFER_ENCODING_ORDINAL:
value=HttpHeaderValues.CACHE.lookup(value);
vo=HttpHeaderValues.CACHE.getOrdinal(value);
if (HttpHeaderValues.CHUNKED_ORDINAL == vo)
_contentLength=HttpTokens.CHUNKED_CONTENT;
else
{
String c=value.toString();
if (c.endsWith(HttpHeaderValues.CHUNKED))
_contentLength=HttpTokens.CHUNKED_CONTENT;
else if (c.indexOf(HttpHeaderValues.CHUNKED) >= 0)
throw new HttpException(400,null);
}
break;
}
}
_handler.parsedHeader(header, value);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
}
// now handle ch
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// End of header
// work out the _content demarcation
if (_contentLength == HttpTokens.UNKNOWN_CONTENT)
{
if (_responseStatus == 0 // request
|| _responseStatus == 304 // not-modified response
|| _responseStatus == 204 // no-content response
|| _responseStatus < 200) // 1xx response
_contentLength=HttpTokens.NO_CONTENT;
else
_contentLength=HttpTokens.EOF_CONTENT;
}
_contentPosition=0;
_eol=ch;
// We convert _contentLength to an int for this switch statement because
// we don't care about the amount of data available just whether there is some.
switch (_contentLength > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) _contentLength)
{
case HttpTokens.EOF_CONTENT:
_state=STATE_EOF_CONTENT;
if(_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.CHUNKED_CONTENT:
_state=STATE_CHUNKED_CONTENT;
if (_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.NO_CONTENT:
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
break;
default:
_state=STATE_CONTENT;
if(_forceContentBuffer ||
(_buffers!=null && _body==null && _buffer==_header && _contentLength>=(_header.capacity()-_header.getIndex())))
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
}
return total_filled;
}
else
{
// New header
_length=1;
_buffer.mark();
_state=STATE_HEADER_NAME;
// try cached name!
if (array!=null)
{
_cached=HttpHeaders.CACHE.getBest(array, _buffer.markIndex(), length+1);
if (_cached!=null)
{
_length=_cached.length();
_buffer.setGetIndex(_buffer.markIndex()+_length);
length=_buffer.length();
}
}
}
}
}
break;
case STATE_HEADER_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
_cached=null;
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_NAME;
}
}
break;
case STATE_HEADER_IN_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_NAME;
break;
default:
{
_cached=null;
_length++;
}
}
break;
case STATE_HEADER_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_VALUE;
}
}
break;
case STATE_HEADER_IN_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_VALUE;
break;
default:
_length++;
}
break;
}
} // end of HEADER states loop
// ==========================
// Handle _content
length=_buffer.length();
if (_input!=null)
_input._contentView=_contentView;
Buffer chunk;
while (_state > STATE_END && length > 0)
{
if (_eol == HttpTokens.CARRIAGE_RETURN && _buffer.peek() == HttpTokens.LINE_FEED)
{
_eol=_buffer.get();
length=_buffer.length();
continue;
}
_eol=0;
switch (_state)
{
case STATE_EOF_CONTENT:
chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
case STATE_CONTENT:
{
long remaining=_contentLength - _contentPosition;
if (remaining == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
if (length > remaining)
{
// We can cast reamining to an int as we know that it is smaller than
// or equal to length which is already an int.
length=(int)remaining;
}
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
if(_contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
}
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
case STATE_CHUNKED_CONTENT:
{
ch=_buffer.peek();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
_eol=_buffer.get();
else if (ch <= HttpTokens.SPACE)
_buffer.get();
else
{
_chunkLength=0;
_chunkPosition=0;
_state=STATE_CHUNK_SIZE;
}
break;
}
case STATE_CHUNK_SIZE:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
else if (ch <= HttpTokens.SPACE || ch == HttpTokens.SEMI_COLON)
_state=STATE_CHUNK_PARAMS;
else if (ch >= '0' && ch <= '9')
_chunkLength=_chunkLength * 16 + (ch - '0');
else if (ch >= 'a' && ch <= 'f')
_chunkLength=_chunkLength * 16 + (10 + ch - 'a');
else if (ch >= 'A' && ch <= 'F')
_chunkLength=_chunkLength * 16 + (10 + ch - 'A');
else
throw new IOException("bad chunk char: " + ch);
break;
}
case STATE_CHUNK_PARAMS:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
break;
}
case STATE_CHUNK:
{
int remaining=_chunkLength - _chunkPosition;
if (remaining == 0)
{
_state=STATE_CHUNKED_CONTENT;
break;
}
else if (length > remaining)
length=remaining;
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_chunkPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
}
length=_buffer.length();
}
return total_filled;
}
/* ------------------------------------------------------------------------------- */
/** fill the buffers from the endpoint
*
*/
public long fill() throws IOException
{
if (_buffer==null)
{
_buffer=_header=getHeaderBuffer();
_tok0=new View.CaseInsensitive(_buffer);
_tok1=new View.CaseInsensitive(_buffer);
}
if (_body!=null && _buffer!=_body)
_buffer=_body;
if (_buffer == _body)
_buffer.compact();
int space=_buffer.space();
// Fill buffer if we can
if (space == 0)
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL "+(_buffer==_body?"body":"head"));
else
{
int filled=-1;
if (_endp != null )
{
try
{
filled=_endp.fill(_buffer);
}
catch(IOException e)
{
Log.debug(e);
reset(true);
throw (e instanceof EofException) ? e:new EofException(e);
}
}
return filled;
}
}
/* ------------------------------------------------------------------------------- */
/** Skip any CRLFs in buffers
*
*/
public void skipCRLF()
{
while (_header!=null && _header.length()>0)
{
byte ch = _header.peek();
if (ch==HttpTokens.CARRIAGE_RETURN || ch==HttpTokens.LINE_FEED)
{
_eol=ch;
_header.skip(1);
}
else
break;
}
while (_body!=null && _body.length()>0)
{
byte ch = _body.peek();
if (ch==HttpTokens.CARRIAGE_RETURN || ch==HttpTokens.LINE_FEED)
{
_eol=ch;
_body.skip(1);
}
else
break;
}
}
/* ------------------------------------------------------------------------------- */
public void reset(boolean returnBuffers)
{
synchronized (this)
{
if (_input!=null && _contentView.length()>0)
_input._contentView=_contentView.duplicate(Buffer.READWRITE);
_state=STATE_START;
_contentLength=HttpTokens.UNKNOWN_CONTENT;
_contentPosition=0;
_length=0;
_responseStatus=0;
if (_buffer!=null && _buffer.length()>0 && _eol == HttpTokens.CARRIAGE_RETURN && _buffer.peek() == HttpTokens.LINE_FEED)
{
_buffer.skip(1);
_eol=HttpTokens.LINE_FEED;
}
if (_body!=null)
{
if (_body.hasContent())
{
_header.setMarkIndex(-1);
_header.compact();
// TODO if pipelined requests received after big input - maybe this is not good?.
_body.skip(_header.put(_body));
}
if (_body.length()==0)
{
if (_buffers!=null && returnBuffers)
_buffers.returnBuffer(_body);
_body=null;
}
else
{
_body.setMarkIndex(-1);
_body.compact();
}
}
if (_header!=null)
{
_header.setMarkIndex(-1);
if (!_header.hasContent() && _buffers!=null && returnBuffers)
{
_buffers.returnBuffer(_header);
_header=null;
_buffer=null;
}
else
{
_header.compact();
_tok0.update(_header);
_tok0.update(0,0);
_tok1.update(_header);
_tok1.update(0,0);
}
}
_buffer=_header;
}
}
/* ------------------------------------------------------------------------------- */
public void setState(int state)
{
this._state=state;
_contentLength=HttpTokens.UNKNOWN_CONTENT;
}
/* ------------------------------------------------------------------------------- */
public String toString(Buffer buf)
{
return "state=" + _state + " length=" + _length + " buf=" + buf.hashCode();
}
/* ------------------------------------------------------------------------------- */
public String toString()
{
return "state=" + _state + " length=" + _length + " len=" + _contentLength;
}
/* ------------------------------------------------------------ */
public Buffer getHeaderBuffer()
{
if (_header == null)
{
_header=_buffers.getBuffer(_headerBufferSize);
}
return _header;
}
/* ------------------------------------------------------------ */
public Buffer getBodyBuffer()
{
return _body;
}
/* ------------------------------------------------------------ */
/**
* @param force True if a new buffer will be forced to be used for content and the header buffer will not be used.
*/
public void setForceContentBuffer(boolean force)
{
_forceContentBuffer=force;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
public static abstract class EventHandler
{
public abstract void content(Buffer ref) throws IOException;
public void headerComplete() throws IOException
{
}
public void messageComplete(long contentLength) throws IOException
{
}
/**
* This is the method called by parser when a HTTP Header name and value is found
*/
public void parsedHeader(Buffer name, Buffer value) throws IOException
{
}
/**
* This is the method called by parser when the HTTP request line is parsed
*/
public abstract void startRequest(Buffer method, Buffer url, Buffer version)
throws IOException;
/**
* This is the method called by parser when the HTTP request line is parsed
*/
public abstract void startResponse(Buffer version, int status, Buffer reason)
throws IOException;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
public static class Input extends ServletInputStream
{
protected HttpParser _parser;
protected EndPoint _endp;
protected long _maxIdleTime;
protected Buffer _contentView;
/* ------------------------------------------------------------ */
public Input(HttpParser parser, long maxIdleTime)
{
_parser=parser;
_endp=parser._endp;
_maxIdleTime=maxIdleTime;
_contentView=_parser._contentView;
_parser._input=this;
}
/* ------------------------------------------------------------ */
/*
* @see java.io.InputStream#read()
*/
public int read() throws IOException
{
int c=-1;
if (blockForContent())
c= 0xff & _contentView.get();
return c;
}
/* ------------------------------------------------------------ */
/*
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException
{
int l=-1;
if (blockForContent())
l= _contentView.get(b, off, len);
return l;
}
/* ------------------------------------------------------------ */
private boolean blockForContent() throws IOException
{
if (_contentView.length()>0)
return true;
if (_parser.getState() <= HttpParser.STATE_END)
return false;
// Handle simple end points.
if (_endp==null)
_parser.parseNext();
// Handle blocking end points
else if (_endp.isBlocking())
{
try
{
_parser.parseNext();
// parse until some progress is made (or IOException thrown for timeout)
while(_contentView.length() == 0 && !_parser.isState(HttpParser.STATE_END))
{
// Try to get more _parser._content
_parser.parseNext();
}
}
catch(IOException e)
{
_endp.close();
throw e;
}
}
else // Handle non-blocking end point
{
_parser.parseNext();
// parse until some progress is made (or IOException thrown for timeout)
while(_contentView.length() == 0 && !_parser.isState(HttpParser.STATE_END))
{
if (!_endp.blockReadable(_maxIdleTime))
{
_endp.close();
throw new EofException("timeout");
}
// Try to get more _parser._content
_parser.parseNext();
}
}
return _contentView.length()>0;
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see java.io.InputStream#available()
*/
public int available() throws IOException
{
if (_contentView!=null && _contentView.length()>0)
return _contentView.length();
if (!_endp.isBlocking())
_parser.parseNext();
return _contentView==null?0:_contentView.length();
}
}
}
| true | true |
public long parseNext() throws IOException
{
long total_filled=-1;
if (_state == STATE_END)
return -1;
if (_buffer==null)
{
if (_header == null)
{
_header=_buffers.getBuffer(_headerBufferSize);
}
_buffer=_header;
_tok0=new View.CaseInsensitive(_header);
_tok1=new View.CaseInsensitive(_header);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
}
if (_state == STATE_CONTENT && _contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
int length=_buffer.length();
// Fill buffer if we can
if (length == 0)
{
int filled=-1;
if (_body!=null && _buffer!=_body)
{
_buffer=_body;
filled=_buffer.length();
}
if (_buffer.markIndex() == 0 && _buffer.putIndex() == _buffer.capacity())
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL");
IOException ioex=null;
if (_endp != null && filled<=0)
{
// Compress buffer if handling _content buffer
// TODO check this is not moving data too much
if (_buffer == _body)
_buffer.compact();
if (_buffer.space() == 0)
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL "+(_buffer==_body?"body":"head"));
try
{
if (total_filled<0)
total_filled=0;
filled=_endp.fill(_buffer);
if (filled>0)
total_filled+=filled;
}
catch(IOException e)
{
Log.debug(e);
ioex=e;
filled=-1;
}
}
if (filled < 0)
{
if ( _state == STATE_EOF_CONTENT)
{
if (_buffer.length()>0)
{
// TODO should we do this here or fall down to main loop?
Buffer chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
}
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
reset(true);
throw new EofException(ioex);
}
length=_buffer.length();
}
// EventHandler header
byte ch;
byte[] array=_buffer.array();
while (_state<STATE_END && length-->0)
{
ch=_buffer.get();
if (_eol == HttpTokens.CARRIAGE_RETURN && ch == HttpTokens.LINE_FEED)
{
_eol=HttpTokens.LINE_FEED;
continue;
}
_eol=0;
switch (_state)
{
case STATE_START:
_contentLength=HttpTokens.UNKNOWN_CONTENT;
_cached=null;
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD0;
}
break;
case STATE_FIELD0:
if (ch == HttpTokens.SPACE)
{
_tok0.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE1;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_SPACE1:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD1;
}
else if (ch < HttpTokens.SPACE)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_FIELD1:
if (ch == HttpTokens.SPACE)
{
_tok1.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE2;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _buffer
.sliceFromMark(), null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_SPACE2:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD2;
}
else if (ch < HttpTokens.SPACE)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _tok1, null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_FIELD2:
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// TODO - we really should know if we are parsing request or response!
final Buffer method = HttpMethods.CACHE.lookup(_tok0);
if (method==_tok0 && _tok1.length()==3 && Character.isDigit(_tok1.peek()))
{
_responseStatus = BufferUtil.toInt(_tok1);
_handler.startResponse(HttpVersions.CACHE.lookup(_tok0), _responseStatus,_buffer.sliceFromMark());
}
else
_handler.startRequest(method, _tok1,HttpVersions.CACHE.lookup(_buffer.sliceFromMark()));
_eol=ch;
_state=STATE_HEADER;
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
continue;
// return total_filled;
}
break;
case STATE_HEADER:
switch(ch)
{
case HttpTokens.COLON:
case HttpTokens.SPACE:
case HttpTokens.TAB:
{
// header value without name - continuation?
_length=-1;
_state=STATE_HEADER_VALUE;
break;
}
default:
{
// handler last header if any
if (_cached!=null || _tok0.length() > 0 || _tok1.length() > 0 || _multiLineValue != null)
{
Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0);
_cached=null;
Buffer value=_multiLineValue == null ? (Buffer) _tok1 : (Buffer) new ByteArrayBuffer(_multiLineValue);
int ho=HttpHeaders.CACHE.getOrdinal(header);
if (ho >= 0)
{
int vo=-1;
switch (ho)
{
case HttpHeaders.CONTENT_LENGTH_ORDINAL:
if (_contentLength != HttpTokens.CHUNKED_CONTENT)
{
_contentLength=BufferUtil.toLong(value);
if (_contentLength <= 0)
_contentLength=HttpTokens.NO_CONTENT;
}
break;
case HttpHeaders.TRANSFER_ENCODING_ORDINAL:
value=HttpHeaderValues.CACHE.lookup(value);
vo=HttpHeaderValues.CACHE.getOrdinal(value);
if (HttpHeaderValues.CHUNKED_ORDINAL == vo)
_contentLength=HttpTokens.CHUNKED_CONTENT;
else
{
String c=value.toString();
if (c.endsWith(HttpHeaderValues.CHUNKED))
_contentLength=HttpTokens.CHUNKED_CONTENT;
else if (c.indexOf(HttpHeaderValues.CHUNKED) >= 0)
throw new HttpException(400,null);
}
break;
}
}
_handler.parsedHeader(header, value);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
}
// now handle ch
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// End of header
// work out the _content demarcation
if (_contentLength == HttpTokens.UNKNOWN_CONTENT)
{
if (_responseStatus == 0 // request
|| _responseStatus == 304 // not-modified response
|| _responseStatus == 204 // no-content response
|| _responseStatus < 200) // 1xx response
_contentLength=HttpTokens.NO_CONTENT;
else
_contentLength=HttpTokens.EOF_CONTENT;
}
_contentPosition=0;
_eol=ch;
// We convert _contentLength to an int for this switch statement because
// we don't care about the amount of data available just whether there is some.
switch (_contentLength > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) _contentLength)
{
case HttpTokens.EOF_CONTENT:
_state=STATE_EOF_CONTENT;
if(_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.CHUNKED_CONTENT:
_state=STATE_CHUNKED_CONTENT;
if (_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.NO_CONTENT:
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
break;
default:
_state=STATE_CONTENT;
if(_forceContentBuffer ||
(_buffers!=null && _body==null && _buffer==_header && _contentLength>=(_header.capacity()-_header.getIndex())))
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
}
return total_filled;
}
else
{
// New header
_length=1;
_buffer.mark();
_state=STATE_HEADER_NAME;
// try cached name!
if (array!=null)
{
_cached=HttpHeaders.CACHE.getBest(array, _buffer.markIndex(), length+1);
if (_cached!=null)
{
_length=_cached.length();
_buffer.setGetIndex(_buffer.markIndex()+_length);
length=_buffer.length();
}
}
}
}
}
break;
case STATE_HEADER_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
_cached=null;
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_NAME;
}
}
break;
case STATE_HEADER_IN_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_NAME;
break;
default:
{
_cached=null;
_length++;
}
}
break;
case STATE_HEADER_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_VALUE;
}
}
break;
case STATE_HEADER_IN_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_VALUE;
break;
default:
_length++;
}
break;
}
} // end of HEADER states loop
// ==========================
// Handle _content
length=_buffer.length();
if (_input!=null)
_input._contentView=_contentView;
Buffer chunk;
while (_state > STATE_END && length > 0)
{
if (_eol == HttpTokens.CARRIAGE_RETURN && _buffer.peek() == HttpTokens.LINE_FEED)
{
_eol=_buffer.get();
length=_buffer.length();
continue;
}
_eol=0;
switch (_state)
{
case STATE_EOF_CONTENT:
chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
case STATE_CONTENT:
{
long remaining=_contentLength - _contentPosition;
if (remaining == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
if (length > remaining)
{
// We can cast reamining to an int as we know that it is smaller than
// or equal to length which is already an int.
length=(int)remaining;
}
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
if(_contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
}
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
case STATE_CHUNKED_CONTENT:
{
ch=_buffer.peek();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
_eol=_buffer.get();
else if (ch <= HttpTokens.SPACE)
_buffer.get();
else
{
_chunkLength=0;
_chunkPosition=0;
_state=STATE_CHUNK_SIZE;
}
break;
}
case STATE_CHUNK_SIZE:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
else if (ch <= HttpTokens.SPACE || ch == HttpTokens.SEMI_COLON)
_state=STATE_CHUNK_PARAMS;
else if (ch >= '0' && ch <= '9')
_chunkLength=_chunkLength * 16 + (ch - '0');
else if (ch >= 'a' && ch <= 'f')
_chunkLength=_chunkLength * 16 + (10 + ch - 'a');
else if (ch >= 'A' && ch <= 'F')
_chunkLength=_chunkLength * 16 + (10 + ch - 'A');
else
throw new IOException("bad chunk char: " + ch);
break;
}
case STATE_CHUNK_PARAMS:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
break;
}
case STATE_CHUNK:
{
int remaining=_chunkLength - _chunkPosition;
if (remaining == 0)
{
_state=STATE_CHUNKED_CONTENT;
break;
}
else if (length > remaining)
length=remaining;
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_chunkPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
}
length=_buffer.length();
}
return total_filled;
}
|
public long parseNext() throws IOException
{
long total_filled=-1;
if (_state == STATE_END)
return -1;
if (_buffer==null)
{
if (_header == null)
{
_header=_buffers.getBuffer(_headerBufferSize);
}
_buffer=_header;
_tok0=new View.CaseInsensitive(_header);
_tok1=new View.CaseInsensitive(_header);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
}
if (_state == STATE_CONTENT && _contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
int length=_buffer.length();
// Fill buffer if we can
if (length == 0)
{
int filled=-1;
if (_body!=null && _buffer!=_body)
{
_buffer=_body;
filled=_buffer.length();
}
if (_buffer.markIndex() == 0 && _buffer.putIndex() == _buffer.capacity())
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL");
IOException ioex=null;
if (_endp != null && filled<=0)
{
// Compress buffer if handling _content buffer
// TODO check this is not moving data too much
if (_buffer == _body)
_buffer.compact();
if (_buffer.space() == 0)
throw new HttpException(HttpStatus.ORDINAL_413_Request_Entity_Too_Large, "FULL "+(_buffer==_body?"body":"head"));
try
{
if (total_filled<0)
total_filled=0;
filled=_endp.fill(_buffer);
if (filled>0)
total_filled+=filled;
}
catch(IOException e)
{
Log.debug(e);
ioex=e;
filled=-1;
}
}
if (filled < 0)
{
if ( _state == STATE_EOF_CONTENT)
{
if (_buffer.length()>0)
{
// TODO should we do this here or fall down to main loop?
Buffer chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
}
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
reset(true);
throw new EofException(ioex);
}
length=_buffer.length();
}
// EventHandler header
byte ch;
byte[] array=_buffer.array();
while (_state<STATE_END && length-->0)
{
ch=_buffer.get();
if (_eol == HttpTokens.CARRIAGE_RETURN && ch == HttpTokens.LINE_FEED)
{
_eol=HttpTokens.LINE_FEED;
continue;
}
_eol=0;
switch (_state)
{
case STATE_START:
_contentLength=HttpTokens.UNKNOWN_CONTENT;
_cached=null;
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD0;
}
break;
case STATE_FIELD0:
if (ch == HttpTokens.SPACE)
{
_tok0.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE1;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_SPACE1:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD1;
}
else if (ch < HttpTokens.SPACE)
{
throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
}
break;
case STATE_FIELD1:
if (ch == HttpTokens.SPACE)
{
_tok1.update(_buffer.markIndex(), _buffer.getIndex() - 1);
_state=STATE_SPACE2;
continue;
}
else if (ch < HttpTokens.SPACE && ch>=0)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _buffer
.sliceFromMark(), null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_SPACE2:
if (ch > HttpTokens.SPACE || ch<0)
{
_buffer.mark();
_state=STATE_FIELD2;
}
else if (ch < HttpTokens.SPACE)
{
// HTTP/0.9
_handler.startRequest(HttpMethods.CACHE.lookup(_tok0), _tok1, null);
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
return total_filled;
}
break;
case STATE_FIELD2:
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// TODO - we really should know if we are parsing request or response!
final Buffer method = HttpMethods.CACHE.lookup(_tok0);
if (method==_tok0 && _tok1.length()==3 && Character.isDigit((char)_tok1.peek()))
{
_responseStatus = BufferUtil.toInt(_tok1);
_handler.startResponse(HttpVersions.CACHE.lookup(_tok0), _responseStatus,_buffer.sliceFromMark());
}
else
_handler.startRequest(method, _tok1,HttpVersions.CACHE.lookup(_buffer.sliceFromMark()));
_eol=ch;
_state=STATE_HEADER;
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
continue;
// return total_filled;
}
break;
case STATE_HEADER:
switch(ch)
{
case HttpTokens.COLON:
case HttpTokens.SPACE:
case HttpTokens.TAB:
{
// header value without name - continuation?
_length=-1;
_state=STATE_HEADER_VALUE;
break;
}
default:
{
// handler last header if any
if (_cached!=null || _tok0.length() > 0 || _tok1.length() > 0 || _multiLineValue != null)
{
Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0);
_cached=null;
Buffer value=_multiLineValue == null ? (Buffer) _tok1 : (Buffer) new ByteArrayBuffer(_multiLineValue);
int ho=HttpHeaders.CACHE.getOrdinal(header);
if (ho >= 0)
{
int vo=-1;
switch (ho)
{
case HttpHeaders.CONTENT_LENGTH_ORDINAL:
if (_contentLength != HttpTokens.CHUNKED_CONTENT)
{
_contentLength=BufferUtil.toLong(value);
if (_contentLength <= 0)
_contentLength=HttpTokens.NO_CONTENT;
}
break;
case HttpHeaders.TRANSFER_ENCODING_ORDINAL:
value=HttpHeaderValues.CACHE.lookup(value);
vo=HttpHeaderValues.CACHE.getOrdinal(value);
if (HttpHeaderValues.CHUNKED_ORDINAL == vo)
_contentLength=HttpTokens.CHUNKED_CONTENT;
else
{
String c=value.toString();
if (c.endsWith(HttpHeaderValues.CHUNKED))
_contentLength=HttpTokens.CHUNKED_CONTENT;
else if (c.indexOf(HttpHeaderValues.CHUNKED) >= 0)
throw new HttpException(400,null);
}
break;
}
}
_handler.parsedHeader(header, value);
_tok0.setPutIndex(_tok0.getIndex());
_tok1.setPutIndex(_tok1.getIndex());
_multiLineValue=null;
}
// now handle ch
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
// End of header
// work out the _content demarcation
if (_contentLength == HttpTokens.UNKNOWN_CONTENT)
{
if (_responseStatus == 0 // request
|| _responseStatus == 304 // not-modified response
|| _responseStatus == 204 // no-content response
|| _responseStatus < 200) // 1xx response
_contentLength=HttpTokens.NO_CONTENT;
else
_contentLength=HttpTokens.EOF_CONTENT;
}
_contentPosition=0;
_eol=ch;
// We convert _contentLength to an int for this switch statement because
// we don't care about the amount of data available just whether there is some.
switch (_contentLength > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) _contentLength)
{
case HttpTokens.EOF_CONTENT:
_state=STATE_EOF_CONTENT;
if(_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.CHUNKED_CONTENT:
_state=STATE_CHUNKED_CONTENT;
if (_body==null && _buffers!=null)
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
case HttpTokens.NO_CONTENT:
_state=STATE_END;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
break;
default:
_state=STATE_CONTENT;
if(_forceContentBuffer ||
(_buffers!=null && _body==null && _buffer==_header && _contentLength>=(_header.capacity()-_header.getIndex())))
_body=_buffers.getBuffer(_contentBufferSize);
_handler.headerComplete(); // May recurse here !
break;
}
return total_filled;
}
else
{
// New header
_length=1;
_buffer.mark();
_state=STATE_HEADER_NAME;
// try cached name!
if (array!=null)
{
_cached=HttpHeaders.CACHE.getBest(array, _buffer.markIndex(), length+1);
if (_cached!=null)
{
_length=_cached.length();
_buffer.setGetIndex(_buffer.markIndex()+_length);
length=_buffer.length();
}
}
}
}
}
break;
case STATE_HEADER_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
_cached=null;
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_NAME;
}
}
break;
case STATE_HEADER_IN_NAME:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.COLON:
if (_length > 0 && _cached==null)
_tok0.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_length=-1;
_state=STATE_HEADER_VALUE;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_NAME;
break;
default:
{
_cached=null;
_length++;
}
}
break;
case STATE_HEADER_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
break;
default:
{
if (_length == -1)
_buffer.mark();
_length=_buffer.getIndex() - _buffer.markIndex();
_state=STATE_HEADER_IN_VALUE;
}
}
break;
case STATE_HEADER_IN_VALUE:
switch(ch)
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
if (_length > 0)
{
if (_tok1.length() == 0)
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
else
{
// Continuation line!
if (_multiLineValue == null) _multiLineValue=_tok1.toString();
_tok1.update(_buffer.markIndex(), _buffer.markIndex() + _length);
_multiLineValue += " " + _tok1.toString();
}
}
_eol=ch;
_state=STATE_HEADER;
break;
case HttpTokens.SPACE:
case HttpTokens.TAB:
_state=STATE_HEADER_VALUE;
break;
default:
_length++;
}
break;
}
} // end of HEADER states loop
// ==========================
// Handle _content
length=_buffer.length();
if (_input!=null)
_input._contentView=_contentView;
Buffer chunk;
while (_state > STATE_END && length > 0)
{
if (_eol == HttpTokens.CARRIAGE_RETURN && _buffer.peek() == HttpTokens.LINE_FEED)
{
_eol=_buffer.get();
length=_buffer.length();
continue;
}
_eol=0;
switch (_state)
{
case STATE_EOF_CONTENT:
chunk=_buffer.get(_buffer.length());
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
case STATE_CONTENT:
{
long remaining=_contentLength - _contentPosition;
if (remaining == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
if (length > remaining)
{
// We can cast reamining to an int as we know that it is smaller than
// or equal to length which is already an int.
length=(int)remaining;
}
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
if(_contentPosition == _contentLength)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
}
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
case STATE_CHUNKED_CONTENT:
{
ch=_buffer.peek();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
_eol=_buffer.get();
else if (ch <= HttpTokens.SPACE)
_buffer.get();
else
{
_chunkLength=0;
_chunkPosition=0;
_state=STATE_CHUNK_SIZE;
}
break;
}
case STATE_CHUNK_SIZE:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
else if (ch <= HttpTokens.SPACE || ch == HttpTokens.SEMI_COLON)
_state=STATE_CHUNK_PARAMS;
else if (ch >= '0' && ch <= '9')
_chunkLength=_chunkLength * 16 + (ch - '0');
else if (ch >= 'a' && ch <= 'f')
_chunkLength=_chunkLength * 16 + (10 + ch - 'a');
else if (ch >= 'A' && ch <= 'F')
_chunkLength=_chunkLength * 16 + (10 + ch - 'A');
else
throw new IOException("bad chunk char: " + ch);
break;
}
case STATE_CHUNK_PARAMS:
{
ch=_buffer.get();
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
if (_chunkLength == 0)
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
return total_filled;
}
else
_state=STATE_CHUNK;
}
break;
}
case STATE_CHUNK:
{
int remaining=_chunkLength - _chunkPosition;
if (remaining == 0)
{
_state=STATE_CHUNKED_CONTENT;
break;
}
else if (length > remaining)
length=remaining;
chunk=_buffer.get(length);
_contentPosition += chunk.length();
_chunkPosition += chunk.length();
_contentView.update(chunk);
_handler.content(chunk); // May recurse here
// TODO adjust the _buffer to keep unconsumed content
return total_filled;
}
}
length=_buffer.length();
}
return total_filled;
}
|
diff --git a/GameRunner.java b/GameRunner.java
index 7f64a81..b0ff307 100644
--- a/GameRunner.java
+++ b/GameRunner.java
@@ -1,81 +1,81 @@
package project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import project.Game.WallDirections;
public class GameRunner {
public static void runGame () {
GameState gs = new GameState();
BufferedReader is = new BufferedReader (new InputStreamReader(System.in));
while (!gs.isGameOver()) {
boolean madeMove = false;
boolean wasInvalid = false;
String input = "";
int x=-1;
int y=-1;
while (!madeMove) {
gs.print(); //print board
if (wasInvalid) {
System.out.println("\"" + input + "\" was invalid");
}
System.out.println("Enter your move ('h' for help, 'q' to quit):");
try {
input = is.readLine();
} catch (IOException e) {
System.out.println("Could not read input");
System.exit(1);
}
if (input.equals("q")) {
System.exit(0);
} else if (input.equals("h")) {
printHelp();
}
// give 'move' as coordinates to spot you want to move to
String[] tokens = input.split(" ");
if (tokens.length == 3) {
try {
x = Integer.parseInt(tokens[0]);
y = Integer.parseInt(tokens[1]);
} catch (Exception e) {
wasInvalid = true;
}
System.out.println(tokens[2]);
if (tokens[2].charAt(0)=='m') { // move
if (!wasInvalid) {
madeMove = gs.move(x, y);
wasInvalid = !madeMove;
}
} else if (tokens[2].charAt(0)=='w') { // wall
if (tokens[2].charAt(1)=='h') {
//horizontal wall
madeMove = gs.placeWall(x, y, WallDirections.h);
wasInvalid = !madeMove;
} else if (tokens[2].charAt(1)=='v') {
//vertical wall
- madeMove = gs.placeWall(x, y, WallDirections.h);
+ madeMove = gs.placeWall(x, y, WallDirections.v);
wasInvalid = !madeMove;
}
} else {
wasInvalid = true;
}
} else {
wasInvalid = true;
}
}
//Game ends
}
}
public static void printHelp () {
System.out.println("To make a move: x y m");
System.out.println("Give coordinates of the space you wish to move to, followed by an m.");
System.out.println("To place a wall: x y w[h|v]");
System.out.print("Give the coordinates of the top left space involved in your wall, ");
System.out.println("followed by wh for a horizonal wall or wv for a vertical wall.");
}
}
| true | true |
public static void runGame () {
GameState gs = new GameState();
BufferedReader is = new BufferedReader (new InputStreamReader(System.in));
while (!gs.isGameOver()) {
boolean madeMove = false;
boolean wasInvalid = false;
String input = "";
int x=-1;
int y=-1;
while (!madeMove) {
gs.print(); //print board
if (wasInvalid) {
System.out.println("\"" + input + "\" was invalid");
}
System.out.println("Enter your move ('h' for help, 'q' to quit):");
try {
input = is.readLine();
} catch (IOException e) {
System.out.println("Could not read input");
System.exit(1);
}
if (input.equals("q")) {
System.exit(0);
} else if (input.equals("h")) {
printHelp();
}
// give 'move' as coordinates to spot you want to move to
String[] tokens = input.split(" ");
if (tokens.length == 3) {
try {
x = Integer.parseInt(tokens[0]);
y = Integer.parseInt(tokens[1]);
} catch (Exception e) {
wasInvalid = true;
}
System.out.println(tokens[2]);
if (tokens[2].charAt(0)=='m') { // move
if (!wasInvalid) {
madeMove = gs.move(x, y);
wasInvalid = !madeMove;
}
} else if (tokens[2].charAt(0)=='w') { // wall
if (tokens[2].charAt(1)=='h') {
//horizontal wall
madeMove = gs.placeWall(x, y, WallDirections.h);
wasInvalid = !madeMove;
} else if (tokens[2].charAt(1)=='v') {
//vertical wall
madeMove = gs.placeWall(x, y, WallDirections.h);
wasInvalid = !madeMove;
}
} else {
wasInvalid = true;
}
} else {
wasInvalid = true;
}
}
//Game ends
}
}
|
public static void runGame () {
GameState gs = new GameState();
BufferedReader is = new BufferedReader (new InputStreamReader(System.in));
while (!gs.isGameOver()) {
boolean madeMove = false;
boolean wasInvalid = false;
String input = "";
int x=-1;
int y=-1;
while (!madeMove) {
gs.print(); //print board
if (wasInvalid) {
System.out.println("\"" + input + "\" was invalid");
}
System.out.println("Enter your move ('h' for help, 'q' to quit):");
try {
input = is.readLine();
} catch (IOException e) {
System.out.println("Could not read input");
System.exit(1);
}
if (input.equals("q")) {
System.exit(0);
} else if (input.equals("h")) {
printHelp();
}
// give 'move' as coordinates to spot you want to move to
String[] tokens = input.split(" ");
if (tokens.length == 3) {
try {
x = Integer.parseInt(tokens[0]);
y = Integer.parseInt(tokens[1]);
} catch (Exception e) {
wasInvalid = true;
}
System.out.println(tokens[2]);
if (tokens[2].charAt(0)=='m') { // move
if (!wasInvalid) {
madeMove = gs.move(x, y);
wasInvalid = !madeMove;
}
} else if (tokens[2].charAt(0)=='w') { // wall
if (tokens[2].charAt(1)=='h') {
//horizontal wall
madeMove = gs.placeWall(x, y, WallDirections.h);
wasInvalid = !madeMove;
} else if (tokens[2].charAt(1)=='v') {
//vertical wall
madeMove = gs.placeWall(x, y, WallDirections.v);
wasInvalid = !madeMove;
}
} else {
wasInvalid = true;
}
} else {
wasInvalid = true;
}
}
//Game ends
}
}
|
diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/WhoCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/WhoCommand.java
index 82a66fb..2ba6539 100644
--- a/src/main/java/com/onarandombox/MultiverseCore/commands/WhoCommand.java
+++ b/src/main/java/com/onarandombox/MultiverseCore/commands/WhoCommand.java
@@ -1,102 +1,102 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
public class WhoCommand extends MultiverseCommand {
private MVWorldManager worldManager;
public WhoCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Who?");
this.setCommandUsage("/mv who" + ChatColor.GOLD + " [WORLD]");
this.setArgRange(0, 1);
this.addKey("mv who");
this.addKey("mvw");
this.addKey("mvwho");
this.setPermission("multiverse.core.list.who", "States who is in what world.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
// If this command was sent from a Player then we need to check Permissions
Player p = null;
// By default, show all from the console
boolean showAll = true;
if (sender instanceof Player) {
p = (Player) sender;
showAll = false;
}
List<MultiverseWorld> worlds = new ArrayList<MultiverseWorld>();
if (args.size() > 0) {
MultiverseWorld world = this.worldManager.getMVWorld(args.get(0));
if (args.get(0).equalsIgnoreCase("--all") || args.get(0).equalsIgnoreCase("-a")) {
showAll = true;
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
} else if (world != null) {
if (!world.isHidden()) {
worlds.add(world);
}
} else {
sender.sendMessage(ChatColor.RED + "World does not exist");
return;
}
} else {
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
}
if (worlds.size() == 0) {
sender.sendMessage("Multiverse does not know about any of your worlds :(");
} else if (worlds.size() == 1) {
sender.sendMessage(ChatColor.AQUA + "--- Players in" + worlds.get(0).getColoredWorldString() + ChatColor.AQUA + " ---");
} else {
sender.sendMessage(ChatColor.AQUA + "--- There are players in ---");
}
for (MultiverseWorld world : worlds) {
if (!(this.worldManager.isMVWorld(world.getName()))) {
continue;
}
if (p != null && (!this.plugin.getMVPerms().canEnterWorld(p, world))) {
continue;
}
List<Player> players = world.getCBWorld().getPlayers();
String result = "";
if (players.size() <= 0 && !showAll) {
continue;
}
if (players.size() <= 0) {
result = "Empty";
} else {
for (Player player : players) {
- result += player.getDisplayName() + " ";
+ result += player.getDisplayName() + " " + ChatColor.WHITE;
}
}
sender.sendMessage(world.getColoredWorldString() + ChatColor.WHITE + " - " + result);
}
}
}
| true | true |
public void runCommand(CommandSender sender, List<String> args) {
// If this command was sent from a Player then we need to check Permissions
Player p = null;
// By default, show all from the console
boolean showAll = true;
if (sender instanceof Player) {
p = (Player) sender;
showAll = false;
}
List<MultiverseWorld> worlds = new ArrayList<MultiverseWorld>();
if (args.size() > 0) {
MultiverseWorld world = this.worldManager.getMVWorld(args.get(0));
if (args.get(0).equalsIgnoreCase("--all") || args.get(0).equalsIgnoreCase("-a")) {
showAll = true;
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
} else if (world != null) {
if (!world.isHidden()) {
worlds.add(world);
}
} else {
sender.sendMessage(ChatColor.RED + "World does not exist");
return;
}
} else {
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
}
if (worlds.size() == 0) {
sender.sendMessage("Multiverse does not know about any of your worlds :(");
} else if (worlds.size() == 1) {
sender.sendMessage(ChatColor.AQUA + "--- Players in" + worlds.get(0).getColoredWorldString() + ChatColor.AQUA + " ---");
} else {
sender.sendMessage(ChatColor.AQUA + "--- There are players in ---");
}
for (MultiverseWorld world : worlds) {
if (!(this.worldManager.isMVWorld(world.getName()))) {
continue;
}
if (p != null && (!this.plugin.getMVPerms().canEnterWorld(p, world))) {
continue;
}
List<Player> players = world.getCBWorld().getPlayers();
String result = "";
if (players.size() <= 0 && !showAll) {
continue;
}
if (players.size() <= 0) {
result = "Empty";
} else {
for (Player player : players) {
result += player.getDisplayName() + " ";
}
}
sender.sendMessage(world.getColoredWorldString() + ChatColor.WHITE + " - " + result);
}
}
|
public void runCommand(CommandSender sender, List<String> args) {
// If this command was sent from a Player then we need to check Permissions
Player p = null;
// By default, show all from the console
boolean showAll = true;
if (sender instanceof Player) {
p = (Player) sender;
showAll = false;
}
List<MultiverseWorld> worlds = new ArrayList<MultiverseWorld>();
if (args.size() > 0) {
MultiverseWorld world = this.worldManager.getMVWorld(args.get(0));
if (args.get(0).equalsIgnoreCase("--all") || args.get(0).equalsIgnoreCase("-a")) {
showAll = true;
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
} else if (world != null) {
if (!world.isHidden()) {
worlds.add(world);
}
} else {
sender.sendMessage(ChatColor.RED + "World does not exist");
return;
}
} else {
worlds = new ArrayList<MultiverseWorld>(this.worldManager.getMVWorlds());
}
if (worlds.size() == 0) {
sender.sendMessage("Multiverse does not know about any of your worlds :(");
} else if (worlds.size() == 1) {
sender.sendMessage(ChatColor.AQUA + "--- Players in" + worlds.get(0).getColoredWorldString() + ChatColor.AQUA + " ---");
} else {
sender.sendMessage(ChatColor.AQUA + "--- There are players in ---");
}
for (MultiverseWorld world : worlds) {
if (!(this.worldManager.isMVWorld(world.getName()))) {
continue;
}
if (p != null && (!this.plugin.getMVPerms().canEnterWorld(p, world))) {
continue;
}
List<Player> players = world.getCBWorld().getPlayers();
String result = "";
if (players.size() <= 0 && !showAll) {
continue;
}
if (players.size() <= 0) {
result = "Empty";
} else {
for (Player player : players) {
result += player.getDisplayName() + " " + ChatColor.WHITE;
}
}
sender.sendMessage(world.getColoredWorldString() + ChatColor.WHITE + " - " + result);
}
}
|
diff --git a/ping-service/src/dmitrygusev/ping/pages/job/Analytics.java b/ping-service/src/dmitrygusev/ping/pages/job/Analytics.java
index 89965c1..178f886 100644
--- a/ping-service/src/dmitrygusev/ping/pages/job/Analytics.java
+++ b/ping-service/src/dmitrygusev/ping/pages/job/Analytics.java
@@ -1,227 +1,227 @@
package dmitrygusev.ping.pages.job;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;
import anjlab.cubics.Cube;
import anjlab.cubics.FactModel;
import anjlab.cubics.aggregate.histogram.HistogramAggregateFactory;
import anjlab.cubics.aggregate.histogram.Histogram.HistogramMergeStrategy;
import anjlab.cubics.aggregate.pie.PieAggregateFactory;
import anjlab.cubics.coerce.IntegerCoercer;
import anjlab.cubics.renders.HtmlRender;
import dmitrygusev.ping.entities.Account;
import dmitrygusev.ping.entities.Job;
import dmitrygusev.ping.entities.JobResult;
import dmitrygusev.ping.pages.Index;
import dmitrygusev.ping.services.Application;
import dmitrygusev.ping.services.JobResultCSVExporter;
import dmitrygusev.ping.services.Utils;
import dmitrygusev.ping.services.dao.JobResultDAO;
@SuppressWarnings("unused")
public class Analytics {
private static final String CSV = "csv";
@Property
private Job job;
private Date dateFrom;
private Date dateTo;
public String getDateFrom() {
return application.formatDate(dateFrom);
}
public String getDateTo() {
return application.formatDate(dateTo);
}
@InjectPage
private Index index;
@Property
@Persist
private String message;
@AfterRender
public void cleanup() {
message = null;
job = null;
view = null;
results = null;
}
@Inject
private Application application;
@Inject
private Request request;
public Index onActivate(Long scheduleId, Long jobId) {
int defaultEnd = 10000;
try {
this.end = request.getParameterNames().contains("end")
? Long.parseLong(request.getParameter("end"))
: defaultEnd;
} catch(Exception e) {
this.end = defaultEnd;
}
try {
job = application.findJob(scheduleId, jobId);
if (job == null) {
index.setExceptionMessage("Job not found");
return index;
}
// Set default view
if (view == null) {
view = DEFAULT_VIEW;
}
initResults();
} catch (Exception e) {
index.setExceptionMessage(e.getMessage());
return index;
}
return null;
}
public Long[] onPassivate() {
if (job != null) {
return Utils.createJobContext(job);
}
return null;
}
@Inject
private JobResultCSVExporter csvExporter;
public StreamResponse onActionFromExportCSV() {
return getExport(CSV);
}
private static final String DEFAULT_VIEW = "year > month > weekOfMonth > day";
@Property
private final String viewModel = DEFAULT_VIEW + ",dayTime > hour,dayOfWeek > month";
@Property
@Persist
private String view;
@Inject
private JobResultDAO jobResultDAO;
private double end;
private List<JobResult> results;
public String getCubeHTML() {
TimeZone timeZone = application.getTimeZone();
for (JobResult result : results) {
result.setTimeZone(timeZone);
}
FactModel<JobResult> model = new FactModel<JobResult>(JobResult.class);
model.setDimensions(view.split(" > "));
model.setMeasures("responseTime", "pingResult");
model.declareCustomAggregate(new PieAggregateFactory<JobResult>(new IntegerCoercer()), "pingResult");
model.declareCustomAggregate(
new HistogramAggregateFactory<JobResult>(HistogramMergeStrategy.NumericRanges, 0, end / 10, end),
"responseTime");
Cube<JobResult> cube = Cube.createCube(model, results);
HtmlRender<JobResult> render = new HtmlRender<JobResult>(cube);
render.getAggregatesOptions("pingResult").
reorder("pie-" + Job.PING_RESULT_OK + "-%", "count", "pie").
exclude("min", "max", "sum", "avg").
setFormat("pie-" + Job.PING_RESULT_OK + "-%", "%.5f").
- setLabel("pie-" + Job.PING_RESULT_OK + "-%", "avail. %").
+ setLabel("pie-" + Job.PING_RESULT_OK + "-%", "%").
setLabel("count", "# of pings").
setLabel("pie", "chart");
render.getAggregatesOptions("responseTime").
reorder("avg").
exclude("count").
setLabel("histogram", "chart");
render.getMeasuresOptions().
setLabel("responseTime", "Response Time, ms").
setLabel("pingResult", "Availability");
render.getDimensionsOptions().
setLabel("all", "All").
setLabel("year", "Year").
setLabel("month", "Month").
setLabel("weekOfMonth", "Week Of Month").
setLabel("day", "Day").
setLabel("hour", "Hour").
setLabel("dayTime", "Day Time").
setLabel("dayOfWeek", "Day Of Week");
return render.render().toString();
}
private void initResults() {
results = jobResultDAO.getResults(job, 1000);
if (results.size() > 0) {
dateTo = results.get(0).getTimestamp();
dateFrom = results.get(results.size() - 1).getTimestamp();
} else {
dateTo = dateFrom = new Date();
}
}
private StreamResponse getExport(final String format) {
return new StreamResponse() {
@Override
public void prepareResponse(Response response) {
response.setHeader(
"Content-Disposition",
"attachment; filename=" + getFilename());
}
private String getFilename() {
return Utils.getCSVExportFilename(job);
}
@Override
public InputStream getStream() throws IOException {
InputStream csvExport = csvExporter.export(results);
return csvExport;
}
@Override
public String getContentType() {
return "text/csv";
}
};
}
}
| true | true |
public String getCubeHTML() {
TimeZone timeZone = application.getTimeZone();
for (JobResult result : results) {
result.setTimeZone(timeZone);
}
FactModel<JobResult> model = new FactModel<JobResult>(JobResult.class);
model.setDimensions(view.split(" > "));
model.setMeasures("responseTime", "pingResult");
model.declareCustomAggregate(new PieAggregateFactory<JobResult>(new IntegerCoercer()), "pingResult");
model.declareCustomAggregate(
new HistogramAggregateFactory<JobResult>(HistogramMergeStrategy.NumericRanges, 0, end / 10, end),
"responseTime");
Cube<JobResult> cube = Cube.createCube(model, results);
HtmlRender<JobResult> render = new HtmlRender<JobResult>(cube);
render.getAggregatesOptions("pingResult").
reorder("pie-" + Job.PING_RESULT_OK + "-%", "count", "pie").
exclude("min", "max", "sum", "avg").
setFormat("pie-" + Job.PING_RESULT_OK + "-%", "%.5f").
setLabel("pie-" + Job.PING_RESULT_OK + "-%", "avail. %").
setLabel("count", "# of pings").
setLabel("pie", "chart");
render.getAggregatesOptions("responseTime").
reorder("avg").
exclude("count").
setLabel("histogram", "chart");
render.getMeasuresOptions().
setLabel("responseTime", "Response Time, ms").
setLabel("pingResult", "Availability");
render.getDimensionsOptions().
setLabel("all", "All").
setLabel("year", "Year").
setLabel("month", "Month").
setLabel("weekOfMonth", "Week Of Month").
setLabel("day", "Day").
setLabel("hour", "Hour").
setLabel("dayTime", "Day Time").
setLabel("dayOfWeek", "Day Of Week");
return render.render().toString();
}
|
public String getCubeHTML() {
TimeZone timeZone = application.getTimeZone();
for (JobResult result : results) {
result.setTimeZone(timeZone);
}
FactModel<JobResult> model = new FactModel<JobResult>(JobResult.class);
model.setDimensions(view.split(" > "));
model.setMeasures("responseTime", "pingResult");
model.declareCustomAggregate(new PieAggregateFactory<JobResult>(new IntegerCoercer()), "pingResult");
model.declareCustomAggregate(
new HistogramAggregateFactory<JobResult>(HistogramMergeStrategy.NumericRanges, 0, end / 10, end),
"responseTime");
Cube<JobResult> cube = Cube.createCube(model, results);
HtmlRender<JobResult> render = new HtmlRender<JobResult>(cube);
render.getAggregatesOptions("pingResult").
reorder("pie-" + Job.PING_RESULT_OK + "-%", "count", "pie").
exclude("min", "max", "sum", "avg").
setFormat("pie-" + Job.PING_RESULT_OK + "-%", "%.5f").
setLabel("pie-" + Job.PING_RESULT_OK + "-%", "%").
setLabel("count", "# of pings").
setLabel("pie", "chart");
render.getAggregatesOptions("responseTime").
reorder("avg").
exclude("count").
setLabel("histogram", "chart");
render.getMeasuresOptions().
setLabel("responseTime", "Response Time, ms").
setLabel("pingResult", "Availability");
render.getDimensionsOptions().
setLabel("all", "All").
setLabel("year", "Year").
setLabel("month", "Month").
setLabel("weekOfMonth", "Week Of Month").
setLabel("day", "Day").
setLabel("hour", "Hour").
setLabel("dayTime", "Day Time").
setLabel("dayOfWeek", "Day Of Week");
return render.render().toString();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.